package store

import (
	"bytes"
	"context"
	"github.com/qiniu/api.v7/v7/auth/qbox"
	"github.com/qiniu/api.v7/v7/storage"
	"mime/multipart"
	"path/filepath"
)

type Qn struct {
	access string
	secret string
	bucket string
	zone   string

	cfg     storage.Config
	upToken string

	mac           *qbox.Mac
	bucketManager *storage.BucketManager
}

var zone_map = map[string]*storage.Zone{
	"huanan":  &storage.ZoneHuanan,
	"huadong": &storage.ZoneHuadong,
	"huabei":  &storage.ZoneHuabei,
	"beimei":  &storage.ZoneBeimei,
}

func NewQn(accessKey, secretKey, bucket, zone string) *Qn {
	qn := &Qn{
		access: accessKey,
		secret: secretKey,
		bucket: bucket,
		zone:   zone,
	}

	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}

	qn.mac = qbox.NewMac(accessKey, secretKey)
	qn.upToken = putPolicy.UploadToken(qn.mac)
	qn.cfg = storage.Config{}
	_, ok := zone_map[zone]
	if ok {
		qn.cfg.Zone = zone_map[zone]
	} else {
		qn.cfg.Zone = &storage.ZoneHuanan
	}
	qn.cfg.UseHTTPS = false
	qn.cfg.UseCdnDomains = false

	qn.bucketManager = storage.NewBucketManager(qn.mac, &qn.cfg)
	return qn
}

/**
上传, 返回上传后的文件名
*/
func (self *Qn) Upload(absfile string) (string, error) {
	formUploader := storage.NewFormUploader(&self.cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{}

	key := filepath.Base(absfile)
	err := formUploader.PutFile(context.Background(), &ret, self.upToken, key, absfile, &putExtra)
	if err != nil {
		return "", err
	}

	return ret.Key, nil
}

func (self *Qn) UploadFormFile(fh *multipart.FileHeader) (string, error) {
	formUploader := storage.NewFormUploader(&self.cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{}

	content := []byte("")
	contentLen := fh.Size
	err := formUploader.PutWithoutKey(context.Background(), &ret, self.upToken,
		bytes.NewReader(content), contentLen, &putExtra)
	if err != nil {
		return "", err
	}

	return ret.Key, nil
}

func (self *Qn) Delete(url string) error {
	key := filepath.Base(url)
	return self.bucketManager.Delete(self.bucket, key)
}
