package cmii_operator

import (
	"github.com/minio/minio-go"
	"os"
	"strings"
)

type CmiiMinioOperator struct {
	LocalEndpoint  string
	PublicEndpoint string

	AccessKeyID     string
	SecretAccessKey string

	LocalClient  *minio.Client
	PublicClient *minio.Client

	OctopusBucketName string
}

const (
	DefaultLocalEndpoint     = "http://10.250.0.100:9000"
	DefaultPublicEndpoint    = "http://42.192.52.227:9000"
	DefaultAccessKeyID       = "cmii"
	DefaultSecretAccessKey   = "B#923fC7mk"
	DefaultOctopusBucketName = "octopus"
)

func (op CmiiMinioOperator) buildCmiiMinioOperator() {

	var err error
	if op.LocalClient == nil {
		// 初始化Minio客户端对象。
		op.LocalClient, err = minio.New(DefaultLocalEndpoint, DefaultAccessKeyID, DefaultSecretAccessKey, false)
		if err != nil {
			log.ErrorF("[buildCmiiMinioOperator] - build for LocalClient error !=> %s", err.Error())
		}
	}

	if op.PublicClient == nil {
		// 初始化Minio客户端对象。
		op.PublicClient, err = minio.New(DefaultPublicEndpoint, DefaultAccessKeyID, DefaultSecretAccessKey, false)
		if err != nil {
			log.ErrorF("[buildCmiiMinioOperator] - build for PublicClient error ! => %s", err.Error())
		}
	}

	log.DebugF("[buildCmiiMinioOperator] - build client success !")
}

func (op CmiiMinioOperator) UploadToLocalOctopus(filePath, fileName string) bool {
	op.buildCmiiMinioOperator()
	return op.uploadToOctopus(op.LocalClient, filePath, fileName)
}

func (op CmiiMinioOperator) UploadToPublicOctopus(filePath, fileName string) bool {

	op.buildCmiiMinioOperator()
	return op.uploadToOctopus(op.PublicClient, filePath, fileName)
}

func (op CmiiMinioOperator) uploadToOctopus(client *minio.Client, filePath, fileName string) bool {

	if !strings.HasSuffix(filePath, "/") {
		filePath += "/"
	}

	// 打开要上传的文件
	file, err := os.Open(filePath + fileName)
	if err != nil {
		log.ErrorF("[uploadToOctopus] - file %s open error! %s", filePath+fileName, err.Error())
	}
	defer file.Close()

	// 使用PutObject上传文件
	n, err := client.PutObject(DefaultOctopusBucketName, fileName, file, -1, minio.PutObjectOptions{})
	if err != nil {
		log.ErrorF("[uploadToOctopus] - upload %s error %s", filePath+fileName, err.Error())
		return false
	}

	log.InfoF("[uploadToOctopus] - uploaded %s of size %d", filePath+fileName, n)
	return true
}
