package storagehandlers

import (
	"io"
	"log"
	"mime/multipart"
	"os"
	"path/filepath"
)

type Fs_Handler struct {
}

func NewFsHandler() *Fs_Handler {
	return &Fs_Handler{}
}
func (f *Fs_Handler) Init() error {
	if _, err := os.Stat(Storagepath); os.IsNotExist(err) {
		return err
	}
	return nil
}

func (f *Fs_Handler) Add(file *multipart.FileHeader, fileId string) error {
	src, err := file.Open()
	if err != nil {
		log.Printf("Error opening file: %v\n", err)
		return err
	}
	defer src.Close()

	extension := filepath.Ext(file.Filename)
	destPath := filepath.Join(Storagepath, fileId+extension)
	dst, err := os.Create(destPath)
	if err != nil {
		log.Println("Error creating file")
		return err
	}
	defer dst.Close()
	if _, err = io.Copy(dst, src); err != nil {
		log.Println("Error copying file")
		return err
	}
	return nil
}

func (f *Fs_Handler) Delete(filename string) error {
	filePath := filepath.Join(Storagepath, filename)
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return err
	}
	return os.Remove(filePath)
}

func (f *Fs_Handler) Get(filename string) (string, error) {
	path := filepath.Join(Storagepath, filename)

	if _, err := os.Stat(path); os.IsNotExist(err) {
		return "", err
	}
	return path, nil
}

func (f *Fs_Handler) List() ([]string, error) {
	files, err := os.ReadDir(Storagepath)
	if err != nil {
		return nil, err
	}
	var filenames []string
	for _, file := range files {
		filenames = append(filenames, file.Name())
	}
	return filenames, nil
}
