package minio

import (
	"context"
	"fmt"
	"io"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/themakers/hlog"
)

type BlobStore struct {
	log   hlog.Logger
	store *minio.Client
}

const bucket = "pair"

func New(ctx context.Context, logger hlog.Logger,
	endpoint, keyID, accessKey, token, region string,
	useSSL bool) (*BlobStore, error) {
	conn, err := minio.New(endpoint,
		&minio.Options{
			Creds:  credentials.NewStaticV4(keyID, accessKey, token),
			Secure: useSSL,
			Region: region,
		},
	)
	if err != nil {
		return nil, err
	}
	fmt.Println("monio", keyID,accessKey,token,region)

	bucketExists, err := conn.BucketExists(ctx, bucket)
	if err != nil {
		return nil, err
	}

	if !bucketExists {
		if err := conn.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}); err != nil {
			return nil, err
		}
	}

	return &BlobStore{
		log:   logger.Module("minio"),
		store: conn,
	}, nil
}

func (bs *BlobStore) PutFile(
	ctx context.Context,
	filename string,
	reader io.Reader,
	size int64) error {
	info, err := bs.store.PutObject(ctx, bucket, filename, reader, size, minio.PutObjectOptions{
		//UserMetadata:            nil,
		//UserTags:                nil,
		//Progress:                nil,
		//ContentType:             "",
		//ContentEncoding:         "",
		//ContentDisposition:      "",
		//ContentLanguage:         "",
		//CacheControl:            "",
		//Mode:                    "",
		//RetainUntilDate:         time.Time{},
		//ServerSideEncryption:    nil,
		//NumThreads:              0,
		//StorageClass:            "",
		//WebsiteRedirectLocation: "",
		//PartSize:                0,
		//LegalHold:               "",
		//SendContentMd5:          false,
		//DisableMultipart:        false,
		//Internal:                minio.AdvancedPutOptions{},
	})
	if err != nil {
		return err
	}
	fmt.Println(info)

	return nil
}

func (bs *BlobStore) DeleteFile(ctx context.Context, id string) error {
	if err := bs.store.RemoveObject(ctx, bucket, id, minio.RemoveObjectOptions{
		//GovernanceBypass: false,
		//VersionID:        "",
		//Internal:         AdvancedRemoveOptions
	}); err != nil {
		return err
	}

	return nil
}
