package oss

import (
	"context"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
)

type QiNiuSdk struct {
	accessKey    string
	secretKey    string
	bucket       string
	hostUrl      string
	formUploader *storage.FormUploader
}

func NewQiNiuSdk(AccessKey, SecretKey, Bucket, HostUrl string) *QiNiuSdk {
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuabei
	cfg.UseHTTPS = false
	cfg.UseCdnDomains = false
	return &QiNiuSdk{
		accessKey:    AccessKey,
		secretKey:    SecretKey,
		bucket:       Bucket,
		hostUrl:      HostUrl,
		formUploader: storage.NewFormUploader(&cfg),
	}
}

func (s *QiNiuSdk) Upload(filePath string, filename string) (url string, err error) {
	var (
		putPolicy = storage.PutPolicy{
			Scope: s.bucket,
		}
		mac      = qbox.NewMac(s.accessKey, s.secretKey)
		upToken  = putPolicy.UploadToken(mac)
		ret      = storage.PutRet{}
		putExtra = storage.PutExtra{}
	)
	if err = s.formUploader.PutFile(context.Background(), &ret, upToken, filename, filePath, &putExtra); err == nil {
		url = s.hostUrl + "/" + ret.Key
	}
	return
}

func (s *QiNiuSdk) GetUpToken() (upToken, hostUrl string) {
	var (
		putPolicy = storage.PutPolicy{
			Scope: s.bucket,
		}
		mac = qbox.NewMac(s.accessKey, s.secretKey)
	)
	upToken = putPolicy.UploadToken(mac)
	hostUrl = s.hostUrl
	return
}
