package aliyun

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"path/filepath"
	"strings"
)

var (
	VoiceFileExt = ".mp3.wma.wav.aac.ra.m4a.flac.ape.ac3.amr"
	ImageFileExt = ".png.jpg.jpeg.gif"
	VideoFileExt = ".mp4.ts.3gp.mpg.mpeg.mpe.dat.vob.asf"
)

type UploadAddress struct {
	Endpoint string
	Bucket   string
	FileName 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
}

func validFileExt(rule string, ext string) bool {
	if strings.Contains(rule, strings.ToLower(ext)) {
		return true
	}
	return false
}

//@rule 规则
func ValidFileExt(rule, filename string) bool {
	if len(filename) == 0 {
		return false
	}
	ext := filepath.Ext(filename)
	return validFileExt(rule, ext)
}