package utils

import (
	"errors"
	"os"
	"strconv"
	"strings"
)

const (
	breakpointDir = "./breakpointDir/"
	finishDir     = "./fileDir/"
)

// BreakPointContinue 断点续传
// content: 文件片段内容
// fileName: 文件名
// contentNumber: 当前片段序号
// contentTotal: 总片段数
// fileMd5: 文件MD5
func BreakPointContinue(content []byte, fileName string, contentNumber int, contentTotal int, fileMd5 string) (string, error) {
	path := breakpointDir + fileMd5 + "/"
	err := os.MkdirAll(path, os.ModePerm)
	if err != nil {
		return path, err
	}
	pathC, err := makeFileContent(content, fileName, path, contentNumber)
	return pathC, err
}

// CheckMd5 检查Md5
func CheckMd5(content []byte, chunkMd5 string) bool {
	fileMd5 := MD5V(content)
	return fileMd5 == chunkMd5
}

// makeFileContent 创建切片内容
func makeFileContent(content []byte, fileName string, FileDir string, contentNumber int) (string, error) {
	if strings.Contains(fileName, "..") || strings.Contains(FileDir, "..") {
		return "", errors.New("文件名或路径不合法")
	}
	path := FileDir + fileName + "_" + strconv.Itoa(contentNumber)
	f, err := os.Create(path)
	if err != nil {
		return path, err
	}
	defer f.Close()
	_, err = f.Write(content)
	if err != nil {
		return path, err
	}
	return path, nil
}

// MakeFile 合并切片文件
func MakeFile(fileName string, FileMd5 string) (string, error) {
	rd, err := os.ReadDir(breakpointDir + FileMd5)
	if err != nil {
		return finishDir + fileName, err
	}
	_ = os.MkdirAll(finishDir, os.ModePerm)
	fd, err := os.OpenFile(finishDir+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o644)
	if err != nil {
		return finishDir + fileName, err
	}
	defer fd.Close()
	for k := range rd {
		content, _ := os.ReadFile(breakpointDir + FileMd5 + "/" + fileName + "_" + strconv.Itoa(k))
		_, err = fd.Write(content)
		if err != nil {
			_ = os.Remove(finishDir + fileName)
			return finishDir + fileName, err
		}
	}
	return finishDir + fileName, nil
}

// RemoveChunk 移除切片
func RemoveChunk(FileMd5 string) error {
	return os.RemoveAll(breakpointDir + FileMd5)
}

// GetBreakpointDir 获取断点续传目录
func GetBreakpointDir() string {
	return breakpointDir
}

// GetFinishDir 获取完成文件目录
func GetFinishDir() string {
	return finishDir
}
