using COSXML;
using LitJson;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XRTool.Util;
using static XunJianDataManager;

public class DownLoadXRManager
{
    public static CredentialConfig cospingzheng;
    public static Dictionary<string, byte[]> downLoadCache = new Dictionary<string, byte[]>();
    public static bool DownLoadForBytes(DownLoadResources msg, Action<byte[]> bytes, Action<float> presson)
    {
        getdata((CredentialConfig c) => {

            choosedownloadtype(msg, bytes, presson);
        });

        return true;
    }

    static void choosedownloadtype(DownLoadResources msg, Action<byte[]> bytes, Action<float> presson)
    {
        DownLoadConfig config = new DownLoadConfig();
        config.bytes = bytes;
        config.presson = presson;
        config.data = msg;
        GameObject go = null;
        if(cospingzheng!=null)
        {

            switch (cospingzheng.drive)
            {
                case "minio":
#if ISLOCAL
                    go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadMinIOXRingItem"));
#else
                    go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadMinIOXRingItem"));
#endif
                    DownLoadMinIOXRItem downLoadMinIOXRItem = go.GetComponent<DownLoadMinIOXRItem>();
                    downLoadMinIOXRItem.startDownload(config);
                    /*
                    //string bucket = data["data"]["bucket"].ToString();
                    //string objectName = data["data"]["bucket"].ToString();
                    string Url = data["url"].ToString();
                    string uuid = data["uuid"].ToString();
                    Debug.Log("DGJ ===> DownLoadForBytes " + msg);
                    RoomFileMinio.Instance.getFile(RoomFileMinio.Instance.bucket, Url, uuid, (RoomFileMinio.RoomFileData roomFile) =>
                    {
                        bytes?.Invoke(roomFile.bytes);
                    });*/
                    break;
                case "COS":
#if ISLOCAL
                    go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadCOSXRingItem"));
#else
                    go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadCOSXRingItem"));
#endif
                    DownLoadCOSXRItem downLoadCOSXRItem = go.GetComponent<DownLoadCOSXRItem>();
                    downLoadCOSXRItem.startDownload(config);
                    break;
                default:
#if ISLOCAL
                    go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadURLXRingItem"));
#else
                    go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadURLXRingItem"));
#endif
                    DownLoadURLXRItem downLoadURLXRItem = go.GetComponent<DownLoadURLXRItem>();
                    downLoadURLXRItem.startDownload(config);
                    break;
            }

        }
        else
        {
#if ISLOCAL
            go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadURLXRingItem"));
#else
            go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadURLXRingItem"));
#endif
            DownLoadURLXRItem downLoadURLXRItem = go.GetComponent<DownLoadURLXRItem>();
            downLoadURLXRItem.startDownload(config);

        }
    }

    public static bool DownLoadForFilePath(DownLoadResources msg, Action<string> bytes, Action<float> presson)
    {
        string Url = "";
        string uuid = "";

        Url = msg.path;
        uuid = msg.uuid;

        if (PlayerPrefs.HasKey(Url))
        {
            if (PlayerPrefs.HasKey(Url + "_"+ uuid))
            {
                if(File.Exists(PlayerPrefs.GetString(Url + "_" + uuid)))
                {

                    bytes?.Invoke(PlayerPrefs.GetString(Url + "_" + uuid));
                    return true;
                }
            }
        }

       
        return DownLoadForBytes(msg, (byte[] fileBytes) => { 
            if(fileBytes!=null)
            {
                if (PlayerPrefs.HasKey(Url) && PlayerPrefs.HasKey(Url + "_" + uuid)&& File.Exists(PlayerPrefs.GetString(Url + "_" + uuid)))
                {
                   bytes?.Invoke(PlayerPrefs.GetString(Url + "_" + uuid));
                }
                else
                {
                    if (PlayerPrefs.HasKey(Url) && File.Exists(PlayerPrefs.GetString(Url )))
                    {
                        File.Delete(PlayerPrefs.GetString(Url));
                    }
                    //文件流信息  
                    //StreamWriter sw;  
                    Stream sw;
                    string path = Application.persistentDataPath + "/DownLoadXR/" + Url.Split("/")[Url.Split("/").Length - 1];
                    Debug.Log("准备存文件===》" + path);
                    FileInfo file = new FileInfo(path);
                    try
                    {

                        if (file.Exists)
                        {
                            file.Delete();
                        }
                        if (!Directory.Exists(Application.persistentDataPath + "/DownLoadXR"))
                        {
                            Directory.CreateDirectory(Application.persistentDataPath + "/DownLoadXR");
                        }
                        //如果此文件存在则打开  
                        //sw = file .Append();  
                        //如果此文件不存在则创建  
                        sw = file.Create();

                        //以行的形式写入信息  
                        //sw.WriteLine(info);  
                        sw.Write(fileBytes, 0, fileBytes.Length);
                        sw.Close();
                        sw.Dispose();
                    }
                    catch
                    {
                        /*
                        JsonData data = new JsonData();
                        data["type"] = "fileError";
                        List<string> backTip = new List<string>();
                        backTip.Add(data.ToJson());
                        backTip.Add(data.ToJson());
                        backTip.Add(data.ToJson());
                        WindowsManager.Instance.show(WindowConfig.windowType.Error, false, WindowsManager.Instance.getErrorData("文件提示", "文件存储失败"+ path, Color.white, "icon", backTip, false, "", 5, "知道了.", "", "").ToJson());
                        */
                    }

                    bytes?.Invoke(path);
                    PlayerPrefs.SetString(Url, path);
                    PlayerPrefs.SetString(Url + "_" + uuid, path);
                }
            }
            else
            {
                bytes?.Invoke(null);
            }
        
        
        }, presson);
    }


    public static bool DownLoadForTexture(DownLoadResources msg, Action<Texture2D> bytes, Action<float> presson)
    {

        return DownLoadForBytes(msg, (byte[] fileBytes) => {
            if (fileBytes != null)
            {
                Texture2D tex = new Texture2D(10,10);
                tex.LoadImage(fileBytes);
                bytes?.Invoke(tex);
            }
            else
            {
                bytes?.Invoke(null);
            }


        }, presson);
    }

    public static DownLoadResources getTestData(string url)
    {
        DownLoadResources dlr = new DownLoadResources();
        dlr.path = XunJianDataManager.Instance.chooseXunJian.url;
        return dlr;
    }
    public static void PutFile(string filePath, string fileName, string objectName, string uuid, int fileSize, Action<string> callBack)
    {
        getdata((CredentialConfig c) => {

            GameObject go = null;
            PutFileData putFileData = new PutFileData();
            putFileData.filePath = filePath;
            putFileData.fileName = fileName;
            putFileData.fileSize = fileSize;
            putFileData.callBack = callBack;
            putFileData.objectName = objectName;
            putFileData.uuid = uuid;
            switch (cospingzheng.drive)
            {
                case "minio":
#if ISLOCAL
                    go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadMinIOXRingItem"));
#else
                    go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadMinIOXRingItem"));
#endif
                    DownLoadMinIOXRItem downLoadMinIOXRItem = go.GetComponent<DownLoadMinIOXRItem>();
                    downLoadMinIOXRItem.startUpLoad(putFileData);
                    break;
                case "COS":
#if ISLOCAL
                    go = GameObject.Instantiate(Resources.Load<GameObject>("DownLoadCOSXRingItem"));
#else
               go = GameObject.Instantiate(GameInit.ablist.LoadAsset<GameObject>("DownLoadCOSXRingItem"));
#endif
                    DownLoadCOSXRItem downLoadCOSXRItem = go.GetComponent<DownLoadCOSXRItem>();
                    downLoadCOSXRItem.startUpLoad(putFileData);
                    break;
            }
            Debug.Log("DGJ PutFile   " + filePath);


        });
      

    }
    public static string getTestData(DownLoadResources url,string drive)
    {
        JsonData data = new JsonData();
        data["drive"] = drive;
        data["url"] = url.path;
        data["uuid"] = url.uuid;
        return data.ToJson();
    }

    static void getdata(Action<CredentialConfig> callback)
    {
        if (cospingzheng == null && HttpEdustryAction.Token != "")
        {
            //获取上传凭证, 根据上传凭证获取的数据初始化 MInio
            WindowsManager.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpEdustryAction.storage_projectCredential, "", (string str) =>
            {
                JsonData data = JsonMapper.ToObject(str);
                cospingzheng = JsonConvert.DeserializeObject<CredentialConfig>(data["data"].ToJson());
                callback.Invoke(cospingzheng);
                TimerMgr.Instance.CreateTimer(() => {
                    cospingzheng = null;
                }, 1800);
            }));

        }
        else
        {
            callback.Invoke(null);
        }
    }

    public class DownLoadUrlConfig
    {
        public string url;
        public Action<byte[]> bytes;
        public Action<float> presson;
    }

    public class DownLoadMinIoConfig
    {
        public string url;
        public Action<byte[]> bytes;
        public Action<float> presson;
        public DownLoadResources data;
    }



    public class PutFileData
    {
        public string filePath;
        public string fileName;
        public int fileSize;
        public string objectName;
        public string uuid;
        public Action<string> callBack;
    }
    public class DownLoadConfig
    {
        public Action<byte[]> bytes;
        public Action<float> presson;
        public DownLoadResources data;
    }


    public class Credential
    {
        public string type { get; set; }
    }

    public class CredentialConfig
    {
        
        public string drive { get; set; }
        public Credentials credentials { get; set; }
        public long startTime { get; set; }
        public long expiredTime { get; set; }
        public string bucket { get; set; }
        public string path { get; set; }
        public string region { get; set; }
        public string host { get; set; }
    }

    public class Credentials
    {
        public string tmpSecretId { get; set; }
        public string tmpSecretKey { get; set; }

        public string token { get; set; }
    }
    public class DownLoadResources
    {
        public int id { get; set; }
        public string path { get; set; }
        public string uuid { get; set; }

        public int loadingMethod { get; set; }
        //   public string name { get; set; }

        public string info { get; set; }
    }
}