package minio

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"io"
	"iot_manager_service/config"
	"iot_manager_service/util/logger"
)

type FileObject struct {
	Bucket     string
	ObjectName string
	ObjectSize int64
	Reader     io.Reader
}

var MinioClient *minio.Client

func InitMinio() {
	cfg := config.Instance()

	client, err := minio.New(cfg.Minio.Endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(cfg.Minio.AccessKey, cfg.Minio.SecretKey, ""),
		Secure: false,
	})
	if err != nil {
		panic(fmt.Sprintf("InitMinio err = %s", err.Error()))
	}
	MinioClient = client
}

func PutFile(fileObject FileObject) error {
	ctx := context.Background()
	//桶是否存在
	exists, _ := MinioClient.BucketExists(ctx, fileObject.Bucket)
	if !exists {
		opts := minio.MakeBucketOptions{
			Region: "cn-north-1",
		}
		//MinioClient.SetBucketPolicy(ctx, fileObject.Bucket, policy.BucketPolicyReadOnly)
		MinioClient.MakeBucket(ctx, fileObject.Bucket, opts)
	}
	_, err := MinioClient.PutObject(ctx, fileObject.Bucket, fileObject.ObjectName, fileObject.Reader, fileObject.ObjectSize,
		minio.PutObjectOptions{})
	if err != nil {
		logger.Logger.Errorf("PutObject fail, err = %s", err.Error())
		return err
	}
	return nil
}

func DeleteObject(bucket, objName string) {
	ops := minio.RemoveObjectOptions{}
	MinioClient.RemoveObject(context.Background(), bucket, objName, ops)
}
