// Copyright (C) 2019 Marius Schellenberger

package fs

import (
	"errors"
	"io"
	"os"
	"path/filepath"
)

type Mode int

const (
	Undefined Mode = iota
	IsDir
	IsFile
)

func (fs *Filesystem) GetFile(path string) (f *os.File, fi os.FileInfo, err error) {
	p := filepath.Join(fs.Base, Clean(path))
	f, err = os.Open(p)
	if err != nil {
		return
	}
	fi, err = f.Stat()
	if err != nil {
		return
	}
	if !fi.Mode().IsRegular() {
		err = os.ErrNotExist
	}
	return
}

func (fs *Filesystem) Mode(path string) (mode Mode, err error) {
	p := filepath.Join(fs.Base, Clean(path))
	fi, err := os.Stat(p)
	if err != nil {
		return
	}
	m := fi.Mode()
	if m.IsDir() {
		mode = IsDir
	} else if m.IsRegular() {
		mode = IsFile
	}
	return
}

func (fs *Filesystem) NewFile(r io.Reader, path, orig, name string) (newfile string, err error) {
	path = Clean(path)
	orig = File(orig)
	name = File(name)
	if name == "" {
		name = orig
	}
	newfile = filepath.Join(path, name)
	err = checkPath(newfile)
	if err != nil {
		return
	}
	f, err := os.OpenFile(filepath.Join(fs.Base, newfile), os.O_RDWR|os.O_CREATE, FileMode)
	if err != nil {
		return
	}
	defer f.Close()
	_, err = io.Copy(f, r)
	return
}

func (fs *Filesystem) Mkdir(path, name string) error {
	dirpath := filepath.Join(Clean(path), Clean(name))
	err := checkPath(dirpath)
	if err != nil {
		return err
	}
	return os.Mkdir(filepath.Join(fs.Base, dirpath), DirMode)
}

func (fs *Filesystem) Move(path, dest, name string) (string, error) {
	if name == "" {
		name = File(path)
	}
	fullpath := filepath.Join(fs.Base, Clean(path))
	if fullpath == fs.Base {
		return "", errors.New("the root path can not be moved")
	}
	newfile := filepath.Join(Clean(dest), Clean(name))
	err := checkPath(newfile)
	if err != nil {
		return "", err
	}
	return newfile, os.Rename(fullpath, filepath.Join(fs.Base, newfile))
}

func (fs *Filesystem) Delete(path string) (removed []string, err error) {
	path = Clean(path)
	fullpath := filepath.Join(fs.Base, path)
	if fullpath == fs.Base {
		return nil, errors.New("the root path can not be deleted")
	}
	fi, err := os.Stat(fullpath)
	if err != nil {
		return
	}
	m := fi.Mode()
	if m.IsDir() {
		removed = fs.RecursiveFiles(path)
		err = os.RemoveAll(fullpath)
	} else if m.IsRegular() {
		removed = []string{path}
		err = os.Remove(fullpath)
	}
	return
}
