package huawei

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

const endpoint = "obs.cn-east-3.myhuaweicloud.com"
const bucketName = "spu3dv1"

func createObsClient() (*obs.ObsClient, error) {
	return obs.New("RA1D7CFVCVKUFX1FHHPB", "cDrR2NgAF2KaA4MRkcK19r93P3P6hLKOPhHvPu9p", endpoint)
}

type OssType struct {
	Url  string
	Size int64
}

var _client *obs.ObsClient = nil

func InitConfig() error {
	c, e := createObsClient()
	if e != nil {
		return e
	}
	_client = c
	return nil
}

func UploadFile(fpath string, obsDir string, name string) (*OssType, error) {
	if _client == nil {
		return nil, fmt.Errorf("obs init error")
	}
	obsClient := _client
	keyFormat := "%s/%s"
	if strings.HasSuffix(obsDir, "/") {
		keyFormat = "%s%s"
	}
	obsname := name
	if len(name) < 2 {
		_, obsname = filepath.Split(fpath)
	}
	obsKey := fmt.Sprintf(keyFormat, obsDir, obsname)
	input := &obs.PutFileInput{}
	input.Bucket = bucketName
	input.Key = obsKey
	input.SourceFile = fpath

	fpathExt := path.Ext(fpath)
	isGzFile := fpathExt == ".gz"
	if isGzFile {
		input.ContentType = "text/plain"
		input.Metadata = map[string]string{"Content-Encoding": "gzip"}
	}
	fmt.Println("writing file", fpath, "=>", obsKey)
	result, err := obsClient.PutFile(input)

	isUploadOk := true

	if err != nil {
		fmt.Println("upload failed try again", err.Error())
		isUploadOk = false
	}

	if result.StatusCode != 200 {
		isUploadOk = false
	}

	if !isUploadOk {
		result, err = obsClient.PutFile(input)

		if err != nil {
			fmt.Println("upload obs fail2", fpath, err.Error())
			return nil, err
		}
		if result.StatusCode != 200 {
			return nil, err
		}
	}

	if isGzFile {
		metaRet, err := obsClient.SetObjectMetadata(&obs.SetObjectMetadataInput{
			Bucket: bucketName,
			Key:    obsKey,
			// ContentEncoding: "gzip",
			// ContentType: "text/plain",
		})
		fmt.Println(metaRet, err)

		if err != nil {
			metaRet, err = obsClient.SetObjectMetadata(&obs.SetObjectMetadataInput{
				Bucket: bucketName,
				Key:    obsKey,
				// ContentEncoding: "gzip",
				// ContentType:     "text/plain",
			})
			fmt.Println(metaRet, err)
		}
	}
	fi, err := os.Stat(fpath)
	size := int64(1)
	if err == nil {
		size = fi.Size()
	}
	return &OssType{Url: fmt.Sprintf("//%s.%s/%s", bucketName, endpoint, obsKey), Size: int64(size)}, nil
}
