using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Minio;
using Minio.DataModel.Args;
using UnityEngine;
using static DownLoadXRManager;

public class DownLoadMinIOXRItem : MonoBehaviour
{
    public DownLoadConfig minioconifg;
    public PutFileData uploadconifg;
    public IMinioClient minio;
    public static Dictionary<string, List<DownLoadConfig>> downLoadingList = new Dictionary<string, List<DownLoadConfig>>();
    public void startDownload(DownLoadConfig conifg)
    {
        minioconifg = conifg;
        InitMaterialMinio();
        StartCoroutine(ReadStreamingAssetsFile());
    }
    public void startUpLoad(PutFileData conifg)
    {
        uploadconifg = conifg;
        InitMaterialMinio();
        StartCoroutine(ReadStreamingUpLoad());
    }
    private void InitMaterialMinio()
    {
        bool isHttps = cospingzheng.host.Contains("https");
        var endpoint = cospingzheng.host.Split("//")[1];
        var accessKey = cospingzheng.credentials.tmpSecretId;//"tr6Nh5D8bnlGaLJE6vb5";
        var secretKey = cospingzheng.credentials.tmpSecretKey;// "aVOYdXLnX4MCiKbit8aomZNWvAx8YSpzhiwzFhrI";
        var minioToken = cospingzheng.credentials.token;
        if (cospingzheng.region != null && !string.IsNullOrEmpty(cospingzheng.region) && cospingzheng.region != "null")
        {
            minio = new MinioClient()
                            .WithEndpoint(endpoint)
                            .WithCredentials(accessKey, secretKey)
                            .WithSessionToken(minioToken)
                            .WithSSL(isHttps)
                            .WithRegion(cospingzheng.region)
                            .Build();



        }
        else
        {
            minio = new MinioClient()
                            .WithEndpoint(endpoint)
                            .WithCredentials(accessKey, secretKey)
                            .WithSessionToken(minioToken)
                            .WithSSL(isHttps)
                            .Build();

        }
    }
    IEnumerator ReadStreamingUpLoad()
    {
        //.cssg-snippet-body-start:[transfer-batch-download-objects]

        // await minio.ListBucketsAsync().ConfigureAwait(false);
        Dictionary<string, string> dicheaders = new Dictionary<string, string>();
        dicheaders.Add("X-Amz-Meta-Uuid", uploadconifg.uuid);
        Debug.Log(cospingzheng.bucket + " " + uploadconifg.filePath + " " + uploadconifg.objectName + " " + uploadconifg.fileSize);
        PutObjectArgs putObjectArgs = new PutObjectArgs()
                                        .WithBucket(cospingzheng.bucket)
                                        .WithObject(uploadconifg.objectName)
                                        .WithFileName(uploadconifg.filePath)
                                        .WithContentType("application/octet-stream")
                                        .WithObjectSize(uploadconifg.fileSize)
                                        .WithHeaders(dicheaders);


        yield return minio.PutObjectAsync(putObjectArgs).ConfigureAwait(false);


        uploadconifg.callBack?.Invoke(uploadconifg.objectName);
    }
    public string localPath;
    IEnumerator ReadStreamingAssetsFile()
    {
        if (!Directory.Exists(Application.persistentDataPath + "/DownLoadXR/"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR/");
        }
       
        Debug.Log("ReadStreamingAssetsFile==cospingzheng.bucket=>" + cospingzheng.bucket +
            "   cosconifg.data.path==>" + minioconifg.data.path +
            "   localPathh==>" + localPath );

        StatObjectArgs statObjectArgs = new StatObjectArgs()
                                              .WithBucket(cospingzheng.bucket)
                                              .WithObject(minioconifg.data.path);
        yield return minio.StatObjectAsync(statObjectArgs);

        byte[] bystes = null;
        Debug.Log(" miniominiominiominiominiominiominiominiominiominio");
        // Get input stream to have content of 'my-objectname' from 'my-bucketname'
        GetObjectArgs getObjectArgs = new GetObjectArgs()
                                          .WithBucket(cospingzheng.bucket)
                                          .WithObject(minioconifg.data.path)
                                          .WithCallbackStream((stream) =>
                                          {
                                              Debug.Log(" WithCallbackStreamWithCallbackStreamWithCallbackStreamWithCallbackStreamWithCallbackStream");
                                              bystes = StreamToBytes(stream);
                                              taskQueue.Enqueue(bystes);
                                              /**/

                                              //  rfd.url = Application.persistentDataPath + "/" + Path.GetFileName(url);


                                          })
                                         ;

        yield return minio.GetObjectAsync(getObjectArgs);


        /*

        Debug.Log(" DGJ  getFile DoSomeWork RunBack");
        PresignedGetObjectArgs args = new PresignedGetObjectArgs()
                                          .WithBucket(cospingzheng.bucket)
                                          .WithObject(minioconifg.data.path)
                                          .WithExpiry(60 * 60 * 24);
        Task<string> tk = minio.PresignedGetObjectAsync(args);

        Debug.Log(" DGJ  getFile DoSomeWork RunBack");
        while (tk.Result == null || tk.Result == "" || bystes == null)
        {
            yield return null;
        }
        Debug.Log(" DGJ  getFile DoSomeWork rfdb" + tk.Result);



        string url = tk.Result;
        rfd.url = url;

        Debug.Log(" DGJ  getFile DoSomeWork rfdb");

        RoomFileDataBack rfdb = new RoomFileDataBack();
        rfdb.rfd = rfd;
        rfdb.Nowfd = Nowfd;
        backQueue.Enqueue(rfdb);
        //  Destroy(this.gameObject);*/
    }

    public static byte[] StreamToBytes(Stream stream)
    {
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);
        stream.Seek(0, SeekOrigin.Begin);
        return bytes;
    }
  

    public Queue<byte[]> taskQueue = new Queue<byte[]>();

    public byte[] readbytes(Stream stream)
    {

        using (Stream fs = stream)
        {
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            return bytes;
        }
    }
    private void Update()
    {
        if (taskQueue.Count > 0)
        {
            var state = taskQueue.Dequeue();

            minioconifg.bytes(state);

        }
    }
}