package storage

import (
	"errors"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"os"
	"path/filepath"

	"git.sp4ke.com/sp4ke/bit4sat/config"
	"git.sp4ke.com/sp4ke/bit4sat/utils"
)

func GetStoreDestination(filename string) string {
	return filepath.Join(config.StoragePath, filename)
}

func StoreFormFile(src multipart.File, filename string) error {
	filePath := GetStoreDestination(filename)
	// If file exists just return
	exists, err := CheckFileExists(filePath)
	if err != nil {
		return err
	}
	if exists {
		log.Printf("file %s exists, skipping write", filename)
		return nil
	}

	fd, err := os.Create(filePath)
	defer fd.Close()
	if err != nil {
		return err
	}

	src.Seek(0, 0)
	_, err = io.Copy(fd, src)

	return err
}

func CheckFileExists(file string) (bool, error) {
	info, err := os.Stat(file)
	if err == nil {
		if info.IsDir() {
			errMsg := fmt.Sprintf("'%s' is a directory", file)
			return false, errors.New(errMsg)
		}

		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err
}

func init() {
	err := utils.Mkdir(config.StoragePath)
	if err != nil {
		log.Fatal(err)
	}

}
