package aliyun

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/astaxie/beego"
	"io"
)

/*
AK  AccessKey 完全访问权限
STS (Security Token Service)  临时访问控制
*/

var (
	Endpoint   string = beego.AppConfig.String("end_point")
	BucketName string = beego.AppConfig.String("bucket_name")
	//BucketNameCdn string = beego.AppConfig.String("bucket_name_cdn")
	//EndpointCdn   string = beego.AppConfig.String("end_point_cdn")
)

type OSSClient struct {
	client *oss.Client
	UpAddr UploadAddress
	Auth   UploadAuth
}

//新建oss-client对象
func NewStsOSSClient(uploadAddress, uploadAuth string) (o *OSSClient, err error) {
	addr, e := ParseUploadAddress(uploadAddress)
	if e != nil {
		err = e
		return
	}
	auth, e := ParseUploadAuth(uploadAuth)
	if e != nil {
		err = e
		return
	}
	o, err = NewOSSClient(addr.Endpoint, auth.AccessKeyId, auth.AccessKeySecret, auth.SecurityToken)
	if err != nil {
		return
	}
	o.UpAddr = addr
	o.Auth = auth
	return
}
func NewOSSClient(ep, key, secret, token string) (o *OSSClient, err error) {
	o = &OSSClient{}
	o.client, err = oss.New(ep, key, secret, oss.SecurityToken(token))
	if err != nil {
		return
	}
	return
}

//简单上传 (通过文件地址)
func (o *OSSClient) PutObjectByUrl(bucketName string, fileName string, url string) error {
	r, err := GetFileFromUrl(url)
	if err != nil {
		return err
	}
	return o.PutObject(bucketName, fileName, r)
}
func (o *OSSClient) PutObjectByUrlDefault(url string) error {
	return o.PutObjectByUrl(o.UpAddr.Bucket, o.UpAddr.FileName, url)
}

//简单上传
func (o *OSSClient) PutObject(bucketName, objKey string, r io.Reader, options ...oss.Option) error {
	bucket, err := o.client.Bucket(bucketName)
	if err != nil {
		return err
	}
	return bucket.PutObject(objKey, r, options...)
}