package Util

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"github.com/gabriel-vasile/mimetype"
)

type FileObject struct {
	Filepath string
	Mimetype string
	Size     int64
}

func WriteFile(fileBytes []byte, acceptedMime string) (FileObject, error) {
	var (
		mime       *mimetype.MIME
		mimeSplit  []string
		file       *os.File
		fi         os.FileInfo
		fileObject FileObject
		err        error
	)

	mime = mimetype.Detect(fileBytes)
	mimeSplit = strings.Split(mime.String(), "/")

	if mimeSplit[0] != acceptedMime {
		return fileObject, errors.New("Invalid filetype provided")
	}

	file, err = ioutil.TempFile(
		fmt.Sprintf(
			"./Frontend/public/%ss/",
			mimeSplit[0],
		),
		fmt.Sprintf(
			"%ss-*%s",
			mimeSplit[0],
			mime.Extension(),
		),
	)

	if err != nil {
		return fileObject, err
	}
	defer file.Close()

	_, err = file.Write(fileBytes)

	fi, err = file.Stat()
	if err != nil {
		return fileObject, err
	}

	fileObject = FileObject{
		Filepath: file.Name(),
		Mimetype: mime.String(),
		Size:     fi.Size(),
	}

	return fileObject, err
}
