using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using COSXML;
using COSXML.Auth;
using COSXML.Model;
using COSXML.Model.Object;
using COSXML.Transfer;
using LitJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;
using XRTool.Util;
using static DownLoadXRManager;

public class DownLoadCOSXRItem : MonoBehaviour
{
    public DownLoadConfig cosconifg;
    public PutFileData uploadconifg;
    public static CosXmlServer materialCosXml;
    public static Dictionary<string, List<DownLoadConfig>> downLoadingList = new Dictionary<string, List<DownLoadConfig>>();
    public void startDownload(DownLoadConfig conifg)
    {
        cosconifg = conifg;
        InitMaterialCos();
        StartCoroutine(ReadStreamingAssetsFile());
    }
    public void startUpLoad(PutFileData conifg)
    {
        uploadconifg = conifg;
        InitMaterialCos();
        StartCoroutine(ReadStreamingUpLoad());
    }
    private void InitMaterialCos()
    {
        CosXmlConfig config = new CosXmlConfig.Builder()
            .IsHttps(true)
            .SetRegion(cospingzheng.region)
            .SetDebugLog(true)
            .Build();
        Debug.Log("ReadStreamingAssetsFile==SetRegion=>" + cospingzheng.region);
        QCloudCredentialProvider cosCredentialProvider = new DefaultSessionQCloudCredentialProvider(
 cospingzheng.credentials.tmpSecretId, cospingzheng.credentials.tmpSecretKey, cospingzheng.expiredTime, cospingzheng.credentials.token);

        Debug.Log("ReadStreamingAssetsFile==tmpSecretId=>" + cospingzheng.credentials.tmpSecretId +
            "   tmpSecretKey==>" + cospingzheng.credentials.tmpSecretKey +
            "   expiredTime==>" + cospingzheng.expiredTime +
            "   sessionToken==>" + cospingzheng.credentials.token);

        materialCosXml = new CosXmlServer(config, cosCredentialProvider);

    }
    IEnumerator ReadStreamingUpLoad()
    {
        if (!Directory.Exists(Application.persistentDataPath + "/DownLoadXR/"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR/");
        }
        //.cssg-snippet-body-start:[transfer-batch-download-objects]
        TransferConfig transferConfig = new TransferConfig();

        // 初始化 TransferManager
        TransferManager transferManager = new TransferManager(materialCosXml, transferConfig);
        // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
        // string localDir = System.IO.Path.GetTempPath();//本地文件夹
        // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
     

        Debug.Log("ReadStreamingAssetsFile==cospingzheng.bucket=>" + cospingzheng.bucket+
            "   uploadconifg.objectName==>" + uploadconifg.objectName +
            "    uploadconifg.filePath==>" + uploadconifg.filePath) ;
        
        PutObjectRequest putrequest = new PutObjectRequest(cospingzheng.bucket, uploadconifg.objectName, uploadconifg.filePath);
        Dictionary<string, string> dicheaders = new Dictionary<string, string>();
        dicheaders.Add("X-Amz-Meta-Uuid", uploadconifg.uuid);
        putrequest.SetRequestHeaders(dicheaders);
        // 下载对象
        COSXMLUploadTask UpLoadTask = new COSXMLUploadTask(putrequest);
        UpLoadTask.SetSrcPath(uploadconifg.filePath);
        // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
        //downloadTask.SetMaxTasks(10);
        UpLoadTask.progressCallback = delegate (long completed, long total)
        {
         //   uploadconifg.presson?.Invoke(completed * 100.0f / total);
            Debug.Log(String.Format("Hjj    UpLoad" + uploadconifg.filePath + "progress = {0:##.##}%", completed * 100.0 / total));
            //showDownLoadPre = completed * 100.0f / total;
        };
        // Debug.Log(downloadMaterial.downLoadPath + "|||||||||  DGJ");
        UpLoadTask.onState += OnStateUpLoadTask;

        UpLoadTask.successCallback += SuccessCallback;
        // listDownLoadTask.Add(downloadTask);
        Task<COSXMLUploadTask.UploadTaskResult> task = null;
        try
        {
            task = transferManager.UploadAsync(UpLoadTask);
        }
        catch (COSXML.CosException.CosClientException clientEx)
        {
            Debug.Log("CosClientException===>" + clientEx);
            //请求失败
        }
        catch (COSXML.CosException.CosServerException serverEx)
        {
            Debug.Log("CosClientException===>" + serverEx);
            //请求失败
        }
        yield return task;
        while (!task.IsCompleted)
        {
            yield return null;
        }
        Debug.Log("ReadStreamingAssetsFile==IsCompleted=>" + task.IsCompleted);
        Debug.Log("ReadStreamingAssetsFile===>" + task.IsFaulted);
        Debug.Log("ReadStreamingAssetsFile===>" + task.IsCompletedSuccessfully);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Status);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Exception);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Result.RawContentBodyString);
        //  Destroy(this.gameObject);
    }
    public string localPath;
    IEnumerator ReadStreamingAssetsFile()
    {
        if(!Directory.Exists(Application.persistentDataPath + "/DownLoadXR/"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR/");
        }
        //.cssg-snippet-body-start:[transfer-batch-download-objects]
        TransferConfig transferConfig = new TransferConfig();

        // 初始化 TransferManager
        TransferManager transferManager = new TransferManager(materialCosXml, transferConfig);
        // String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键
        // string localDir = System.IO.Path.GetTempPath();//本地文件夹
        // string localFileName = "my-local-temp-file"; //指定本地保存的文件名
       localPath = Application.persistentDataPath + "/DownLoadXR/" + cosconifg.data.path.Split("/")[cosconifg.data.path.Split("/").Length - 1];
        string localFileName = Path.GetFileName(localPath);

        Debug.Log("ReadStreamingAssetsFile==cospingzheng.bucket=>" + cospingzheng.bucket +
            "   cosconifg.data.path==>" + cosconifg.data.path +
            "   localPathh==>" + localPath +
            "   localFileName==>" + localFileName);

        // 下载对象
        COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(cospingzheng.bucket, cosconifg.data.path,
          Application.persistentDataPath + "/DownLoadXR/", localFileName);
        // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持!
        //downloadTask.SetMaxTasks(10);
        downloadTask.progressCallback = delegate (long completed, long total)
        {
            cosconifg.presson?.Invoke(completed * 100.0f / total);
            Debug.Log(String.Format("Hjj    download"+ cosconifg.data.path + "progress = {0:##.##}%", completed * 100.0 / total));
            //showDownLoadPre = completed * 100.0f / total;
        };
       // Debug.Log(downloadMaterial.downLoadPath + "|||||||||  DGJ");
        downloadTask.onState += OnState;

        downloadTask.successCallback += SuccessCallback;
        // listDownLoadTask.Add(downloadTask);
        Task<COSXMLDownloadTask.DownloadTaskResult> task = null;
        try
        {
            task = transferManager.DownloadAsync(downloadTask);
        }
        catch (COSXML.CosException.CosClientException clientEx)
        {
            Debug.Log("CosClientException===>" + clientEx);
            //请求失败
        }
        catch (COSXML.CosException.CosServerException serverEx)
        {
            Debug.Log("CosClientException===>" + serverEx);
            //请求失败
        }
        yield return task;
        while(!task.IsCompleted)
        {
            yield return null;
        }
        Debug.Log("ReadStreamingAssetsFile==IsCompleted=>" + task.IsCompleted);
        Debug.Log("ReadStreamingAssetsFile===>" + task.IsFaulted);
        Debug.Log("ReadStreamingAssetsFile===>" + task.IsCompletedSuccessfully);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Status);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Exception);
        Debug.Log("ReadStreamingAssetsFile===>" + task.Result.RawContentBodyString);
        //  Destroy(this.gameObject);
    }

    private void OnStateUpLoadTask(TaskState taskState)
    {
        taskUploadQueue.Enqueue(taskState);
    }

    private void SuccessCallback(CosResult cosResult)
    {
        if(cosResult.IsSuccessful())
        {
            Debug.Log("SuccessCallback===>" + cosResult.httpMessage);
            Debug.Log("SuccessCallback===>" + cosResult.httpCode);
            Debug.Log("SuccessCallback===>" + cosResult.Key);
           
        }
    }

    public Queue<TaskState> taskQueue = new Queue<TaskState>();
    public Queue<TaskState> taskUploadQueue = new Queue<TaskState>();
    private void OnState(TaskState state)
    {
        taskQueue.Enqueue(state);
    }
    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();

            if (state == TaskState.Completed || state == TaskState.Failed)
            {
                if (state == TaskState.Completed)
                {
                    FileInfo file = new FileInfo(localPath);
                    cosconifg.bytes(readbytes(file.OpenRead()));
                }
                Debug.Log("Hjj    download" + cosconifg.data.path + "TaskState.=>" + state);
            }

        }
        if (taskUploadQueue.Count > 0)
        {
            var state = taskUploadQueue.Dequeue();

            if (state == TaskState.Completed || state == TaskState.Failed)
            {
                uploadconifg.callBack?.Invoke(state.ToString());
            }

        }
    }
}