package oss

import (
	"bytes"
	"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
}

func NewQiNiuSdk(AccessKey, SecretKey, Bucket, HostUrl string) *QiNiuSdk {
	return &QiNiuSdk{
		accessKey: AccessKey,
		secretKey: SecretKey,
		bucket:    Bucket,
		hostUrl:   HostUrl,
	}
}

func (s *QiNiuSdk) Upload(data []byte, dataLen int64, filename string) (url string, err error) {
	var (
		putPolicy = storage.PutPolicy{
			Scope: s.bucket,
		}
		mac     = qbox.NewMac(s.accessKey, s.secretKey)
		upToken = putPolicy.UploadToken(mac)
		cfg     = storage.Config{}
	)
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuabei
	cfg.UseHTTPS = false
	cfg.UseCdnDomains = false
	var (
		formUploader = storage.NewFormUploader(&cfg)
		ret          = storage.PutRet{}
		putExtra     = storage.PutExtra{}
	)
	if err = formUploader.Put(context.Background(), &ret, upToken, filename, bytes.NewReader(data), dataLen, &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
}
