package tools

import (
	"errors"
	"fmt"
	"github.com/gabriel-vasile/mimetype"
	"github.com/levigross/grequests"
	"net/http"
	"os"
	"time"
)

// GetContentTypeByFilePath 通过文件路径获取ContentType
func GetContentTypeByFilePath(filePath string) *mimetype.MIME {
	f, _ := os.ReadFile(filePath)
	return mimetype.Detect(f)
}

// GetContentTypeByBytes 通过Byte获取ContentType
func GetContentTypeByBytes(bytes []byte) *mimetype.MIME {
	return mimetype.Detect(bytes)
}

// FileExists 判断文件是否存在
func FileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	if err == nil || !os.IsNotExist(err) {
		return true
	}
	return false
}

// FileExistsAndSize 判断文件是否存在且返回体积(byte)
func FileExistsAndSize(filePath string) (bool, int64) {
	stat, err := os.Stat(filePath)
	if (err == nil || !os.IsNotExist(err)) && stat != nil {
		return true, stat.Size()
	}
	return false, 0
}

// DownloadFile 下载图片
func DownloadFile(url, path, name string) error {
	response, err := grequests.Get(url, &grequests.RequestOptions{
		DialKeepAlive:  0 * time.Second,
		DialTimeout:    30 * time.Second,
		RequestTimeout: 30 * time.Second,
	})
	if err != nil {
		return errors.New(fmt.Sprintf("[DownloadError]%s", err.Error()))
	}
	if response.StatusCode != http.StatusOK {
		return errors.New(fmt.Sprintf("[DownloadError][%d]%s", response.StatusCode, response.String()))
	}

	err = os.MkdirAll(path, os.ModePerm)
	if err != nil {
		return err
	}

	fp := path + "/" + name
	err = response.DownloadToFile(fp)
	if err != nil {
		return err
	}
	err = os.Chmod(fp, os.ModePerm)
	if err != nil {
		return err
	}

	return nil
}
