package aliyun

import (
	"bufio"
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

type UploadAddress struct {
	Endpoint string
	Bucket   string
	FileName string
}

type UploadAuth struct {
	SecurityToken   string //sts
	AccessKeyId     string
	AccessKeySecret string
	Expiration      string
	Region          string
}

//@cname 绑定域名
func (up UploadAddress) GetFileUrl(cname string) string {
	if len(cname) > 0 {
		return fmt.Sprintf("%v%v", cname, up.FileName)
	}
	if strings.Contains(up.Endpoint, "https") {
		return fmt.Sprintf("%v%v.%v/%v", up.Endpoint[:8], up.Bucket, up.Endpoint[8:], up.FileName)
	} else if strings.Contains(up.Endpoint, "http") {
		return fmt.Sprintf("%v%v.%v/%v", up.Endpoint[:7], up.Bucket, up.Endpoint[7:], up.FileName)
	}
	return ""
}

//解析UploadAddress
func ParseUploadAddress(uploadAddress string) (up UploadAddress, err error) {
	var jsData []byte
	jsData, err = base64.StdEncoding.DecodeString(uploadAddress)
	if err != nil {
		return
	}
	if err = json.Unmarshal(jsData, &up); err != nil {
		return
	}
	return
}

//解析UploadAddress
func ParseUploadAuth(uploadAuth string) (up UploadAuth, err error) {
	var jsData []byte
	jsData, err = base64.StdEncoding.DecodeString(uploadAuth)
	if err != nil {
		return
	}
	if err = json.Unmarshal(jsData, &up); err != nil {
		return
	}
	return
}

//从文件地址下载数据
func GetFileFromUrl(url string) (r io.Reader, err error) {
	if !strings.Contains(url, "http") {
		return nil, fmt.Errorf("异常路径:%v", url)
	}
	//下载
	rsp, err := http.Get(strings.TrimSpace(url))
	if err != nil {
		return
	}
	var buf *bytes.Buffer = bytes.NewBuffer(nil)
	buf.ReadFrom(rsp.Body)
	r = bufio.NewReader(buf)
	defer rsp.Body.Close()
	if err != nil {
		return
	}
	return
}