using LitJson;
using Minio;
using Minio.DataModel.Args;
using Minio.DataModel.Encryption;
using Minio.Exceptions;
using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;

public class TestMinIO : MonoBehaviour
{
    private string endpoint;
    private string accessKey;
    private string secretKey;
    private string minioToken;
    private string bucketName;
    private string objectName;
    private string contentType;
    private string tmpSecretId;
    private string tmpSecretKey;
    private string host;
    private string path;
    private MinioClient minio;

    private void Start()
    {
        endpoint = "api-fat2.ghz-tech.com";
        accessKey = "2RB1QSM6ZTPQPJIA32K3";
        secretKey = "c1e274Rj0ObD10cHOygHXV2wMZHcFubes0jOza6r";
        minioToken = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiIyUkIxUVNNNlpUUFFQSklBMzJLMyIsImV4cCI6MTY5OTgwOTE0MSwicGFyZW50IjoiZ2h6Iiwic2Vzc2lvblBvbGljeSI6ImV5SjJaWEp6YVc5dUlqb2lNakF4TWkweE1DMHhOeUlzSW5OMFlYUmxiV1Z1ZENJNlczc2lZV04wYVc5dUlqcGJJbk16T2tkbGRFSjFZMnRsZEV4dlkyRjBhVzl1SWl3aWN6TTZSMlYwVDJKcVpXTjBJaXdpY3pNNlVIVjBUMkpxWldOMElpd2ljek02VEdsemRFSjFZMnRsZENKZExDSmxabVpsWTNRaU9pSkJiR3h2ZHlJc0luSmxjMjkxY21ObElqcGJJbUZ5YmpwaGQzTTZjek02T2pvcUlsMTlYWDA9In0.SNxgRP-vBxKvBRwo2pWGcpD3Yap7bjN34jbsluY4pEa45zPmyRSWW-PxvMc69lTaXub2ijYgyPFwOe0iVi7ZMQ";
        bucketName = "ghz";
        objectName = "110901.jpg";
        contentType = "application/octet-stream";
        Active();
        /*
        */
        InspectionCredential();
    }

    private void InspectionCredential()
    {
        JsonData data = new JsonData();
        data["inspectionId"] = 10;
        GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp("/cmcc-endustry/v1/storage/inspectionCredential", data.ToJson(), async (string str) =>
        {
            JsonData d = JsonMapper.ToObject(str);
            //minioToken = d["data"]["credentials"]["token"].ToString();
            tmpSecretId = d["data"]["credentials"]["tmpSecretId"].ToString();
            //tmpSecretKey = d["data"]["credentials"]["tmpSecretKey"].ToString();
            host = d["data"]["host"].ToString();
            bucketName = d["data"]["bucket"].ToString();
            path = d["data"]["path"].ToString();
            Debug.Log(str);
            bool isHttps = host.Contains("https");
            //var endpoint = host.Split("//")[1];
            //var accessKey = tmpSecretId;//"tr6Nh5D8bnlGaLJE6vb5";
            //var secretKey = tmpSecretKey;// "aVOYdXLnX4MCiKbit8aomZNWvAx8YSpzhiwzFhrI";
            //Active();
            
            minio = (MinioClient)new MinioClient()
                            .WithEndpoint(endpoint)
                            .WithCredentials(accessKey, secretKey)
                            .WithSessionToken(minioToken)
                            .WithSSL(isHttps)
                            .Build();
            //  Run((MinioClient)minio).Wait();
            var getListBucketsTask = await minio.ListBucketsAsync().ConfigureAwait(false);
            foreach (var bucket in getListBucketsTask.Buckets)
            {
                Debug.LogError($"Bucket:{bucket.Name}");
            }
            Active();
        }));
    }

    private void Active()
    {
        try
        {
            /*
            var minio = (MinioClient)new MinioClient()
                               //.WithEndpoint(endpoint)
                                .WithEndpoint(host)
                                .WithCredentials(accessKey, secretKey)
                                .WithSessionToken(minioToken)
                                .WithSSL()
                                .Build();
            */
            SetObjectRun(minio).Wait();
            //GetObjectRun(minio, "bluebucketone", "BlueIOTest.jpg", "C:\\Users\\lsxk0\\Desktop\\DownAPK\\1107.jpg").Wait();
        }
        catch (Exception ex)
        {
            Debug.LogError("host:"+ host);
            Debug.LogError("bucketName:" + bucketName);
            Debug.LogError("path:" + path);
            Debug.LogError($"SetObjectRun Error----{ex.Message}");
        }
    }

    /// <summary>
    ///  �ļ��ϴ�
    /// </summary>
    private async Task SetObjectRun(MinioClient minio)
    {
        Debug.LogError("SetObjectRun");

        //var location = "us-east-1";
        var filePath = "C:\\Users\\lsxk0\\Desktop\\ͼƬ\\IMG_20190113_082755.jpg";
        //var filePath = Application.persistentDataPath + "/IMG.jpg";

        try
        {
            // �ڷ�����������һ��bucket�������û�У�
            var beArgs = new BucketExistsArgs()
                .WithBucket(bucketName);
            bool found = await minio.BucketExistsAsync(beArgs).ConfigureAwait(false);
            if (!found)
            {
                var mbArgs = new MakeBucketArgs()
                    .WithBucket(bucketName);
                await minio.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }
            // ���ļ��ϴ���bucket
            var putObjectArgs = new PutObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithFileName(filePath)
                .WithContentType(contentType);
            await minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
            Debug.LogError("Successfully uploaded " + objectName);
        }
        catch (MinioException e)
        {
            Debug.LogError("Upload Error----");
            Debug.LogError($"File Upload Error: {e.Message}");
        }
    }

    /// <summary>
    /// �������bucket���ص������ļ�
    /// </summary>
    public async Task GetObjectRun(
        IMinioClient minio,
        string bucketName = "my-bucket-name",
        string objectName = "my-object-name",
        string fileName = "local-filename",
        IServerSideEncryption sse = null)
    {
        try
        {
            File.Delete(fileName);
            var args = new GetObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithFile(fileName)
                .WithServerSideEncryption(sse);
            _ = await minio.GetObjectAsync(args).ConfigureAwait(false);
            Debug.LogError($"Downloaded the file {fileName} from bucket {bucketName}");
        }
        catch (Exception e)
        {
            Debug.LogError($"[Bucket]  Exception: {e}");
        }
    }
}