package services

import (
	"bytes"
	"filesdk"
	"github.com/kataras/iris/v12"

	"io"
	"sparrow/pkg/models"
	"sparrow/pkg/server"
)

type FileService interface {
	Upload(ctx iris.Context, formKey, bucket string) (*models.FileInfo, error)
}

type fileService struct {
}

func NewFileService() FileService {
	return &fileService{}
}

func (p *fileService) Upload(ctx iris.Context, formKey, bucket string) (*models.FileInfo, error) {
	file, header, err := ctx.FormFile(formKey)
	if err != nil {
		return nil, err
	}
	buff := new(bytes.Buffer)
	_, err = io.Copy(buff, file)
	if err != nil {
		return nil, err
	}
	headers := map[string]string{}
	headers["FILE-EXPIRE"] = "720"
	result, err := filesdk.GetHandle().Upload(header.Filename, bucket, headers, buff.Bytes())
	if err != nil {
		server.Log.Errorf("upload file error : %v", err)
		return nil, err
	}
	err = filesdk.GetHandle().HandlePersistent(result.Hash)
	if err != nil {
		server.Log.Errorf("file handlePersistent error : %v", err)
	}
	info := &models.FileInfo{
		URL:  result.URL,
		Name: result.Name,
		Size: result.Size,
		MD5:  result.Hash,
	}

	return info, nil
}
