// =================================================================================
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
// =================================================================================

package files

import (
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gregex"
	"os"
	"strconv"
	"strings"
)

func (c *ControllerV1) validateFileName(fileName string) error {
	if len(fileName) > 256 {
		return gerror.New("File name exceeds 256 bytes limit")
	}

	if ok := gregex.IsMatchString(`[<>:"/\\|?*\x00-\x1F]`, fileName); ok {
		return gerror.New("File name contains invalid characters")
	}

	return nil
}

func (c *ControllerV1) validateFilePath(filePath string) error {
	if filePath == "/" {
		return gerror.New("Cannot use system root directory")
	}

	if strings.Contains(filePath, "./") {
		return gerror.New("Invalid path parameter")
	}

	return nil
}

func (c *ControllerV1) checkFileExists(filePath string) error {
	if !gfile.Exists(filePath) {
		return gerror.New("File not found")
	}
	return nil
}

func (c *ControllerV1) getFileInfo(filePath string) (*os.FileInfo, error) {
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		return nil, gerror.New("Failed to get file info: " + err.Error())
	}
	return &fileInfo, nil
}

func (c *ControllerV1) validateFileSize(actualSize int64, expectedSize int64) bool {
	return actualSize == expectedSize
}

func (c *ControllerV1) openFileForWrite(filePath string) (*os.File, error) {
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return nil, gerror.New("Failed to open file: " + err.Error())
	}
	return file, nil
}

func (c *ControllerV1) readFileContent(filePath string) ([]byte, error) {
	data, err := os.ReadFile(filePath)
	if err != nil {
		return nil, gerror.New("Failed to read file: " + err.Error())
	}
	return data, nil
}

func (c *ControllerV1) parseMode(mode string) (os.FileMode, error) {
	var parsed uint64
	var err error
	if mode != "" {
		parsed, err = strconv.ParseUint(mode, 8, 32)
		if err != nil {
			return 0, gerror.New("Invalid mode format: " + err.Error())
		}
	}
	return os.FileMode(parsed), nil
}

func (c *ControllerV1) ensureDirectory(path string, mode string) error {
	if path == "" {
		return gerror.New("Directory path cannot be empty")
	}

	// set default directory permissions
	dirMode := os.FileMode(0755)
	if mode != "" {

		var err error
		dirMode, err = c.parseMode(mode)
		if err != nil {
			return err
		}
	}

	if err := os.MkdirAll(path, dirMode); err != nil {
		return gerror.New("Failed to create directory: " + err.Error())
	}
	return nil
}

func (c *ControllerV1) setFilePermission(path string, mode string) error {
	if mode == "" {
		// 默认文件权限0644
		return os.Chmod(path, 0644)
	}

	fileMode, err := c.parseMode(mode)
	if err != nil {
		return err
	}

	return os.Chmod(path, fileMode)
}
