package utils

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/google/uuid"
	"io"
	"path"
	"time"
)

type RouterConfig struct {
	OssEndPoint     string
	AccessKeyID     string
	AccessKeySecret string
	BuckName        string
	AppProject      string

	RegionID string
	RoleArn  string
}

type (
	CreateStsAuthRequest struct {
		Files []string `json:"files"`
	}
	CreateStsAuthResponse struct {
		Certificate interface{}  `json:"certificate"`
		Files       []BuckObject `json:"files"`
	}

	Object struct {
		Key   string
		Value io.Reader
	}
	BuckObject struct {
		DefaultHost string `json:"host"`
		Key         string `json:"key"`
		Path        string `json:"path"`
		FileName    string `json:"fileName"`
	}
)

func NewBucket(config RouterConfig) (*oss.Bucket, error) {
	client, err := oss.New(config.OssEndPoint, config.AccessKeyID, config.AccessKeySecret)
	if err != nil {
		return nil, err
	}
	bucket, err := client.Bucket(config.BuckName)
	if err != nil {
		return nil, err
	}

	return bucket, nil
}

func CreateObjects(bucket *oss.Bucket, objects ...Object) error {
	for _, object := range objects {
		err := bucket.PutObject(object.Key, object.Value)
		if err != nil {
			return err
		}
	}
	return nil
}

func DeleteObjects(bucket *oss.Bucket, objects ...string) error {
	for _, object := range objects {
		err := bucket.DeleteObject(object)
		if err != nil {
			return err
		}
	}
	return nil
}

func GetFileName(projectName, filename string) string {
	date := time.Now().Format("20060102")
	ext := path.Ext(filename)
	if len(projectName) == 0 {
		projectName = "default"
	}
	uid, _ := uuid.NewUUID()
	filename = fmt.Sprintf("%v%v", uid.String(), ext)
	sourcePath := fmt.Sprintf("%v/%v/%v", projectName, date, filename)
	return sourcePath
}