package file

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"skapp/pkg/utils/json"
)

type Support struct {
}

func New() *Support {
	return &Support{}
}

func (s *Support) IsFile(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}

	return !info.IsDir()
}

func (s *Support) IsDir(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}

	return info.IsDir()
}

func (s *Support) CopyN(w io.Writer, path string, n int64) (int64, error) {
	if s.IsDir(path) {
		return 0, errors.New(fmt.Sprintf("%s 为文件夹", path))
	}

	file, err := os.Open(path)
	defer func(file *os.File) {
		_ = file.Close()
	}(file)

	if err != nil {
		return 0, err
	}

	info, _ := file.Stat()
	if n <= 0 {
		return io.Copy(w, file)
	}

	if info.Size() < n {
		return io.Copy(w, file)
	} else {
		return io.CopyN(w, file, n)
	}
}

func (s *Support) SaveJSONFile(filePath string, data interface{}) error {
	if !filepath.IsAbs(filePath) {
		root, _ := os.Getwd()
		filePath = filepath.Join(root, filePath)
	}

	jsonFile, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	defer func(scmF *os.File) {
		_ = scmF.Close()
	}(jsonFile)
	if err != nil {
		return err
	}

	_, err = jsonFile.WriteString(json.Json(data))
	return err
}
