using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class GameInit : MonoBehaviour
{
    public Text text;
    public Text text2;

    public Slider slider;
    string HotUpdateAllAssets = "HotUpdateAllAssets";
    void Start()
    {
        text.text = "正在下载主要资源";
        this.transform.SetParent(OpenXRCamera.Instance.head.transform);
        this.transform.localPosition = Vector3.zero;
        this.transform.localEulerAngles = Vector3.zero;

        JsonData data = new JsonData();
        string scUrl = "";
        try
        {
            data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);

            scUrl = data[HotUpdateAllAssets].ToString();



        }
        catch
        {

        }
        if(scUrl!="")
        {

            if (!bool.Parse(data["isHotUpdate"].ToString()))
            {
                StartCoroutine(DownLoadAssets(false));

            }
            else if (PlayerPrefs.GetString("HotUpdateVersion") == data["HotUpdateVersion"].ToString())
            {
                StartCoroutine(DownLocalLoadAssets());
            }
            else
            {
                StartCoroutine(DownLoadAssets());
            }
        }else
        {
            StartCoroutine(DownLoadAssets(false));

        }
    }

    public static AssetBundle ablist;

    IEnumerator DownLocalLoadAssets()
    {

        string filePath = PlayerPrefs.GetString(HotUpdateAllAssets);
        Task<byte[]> Tb2 = File.ReadAllBytesAsync(filePath);
        yield return Tb2;

        text.text = "正在解析配置";
        slider.gameObject.SetActive(false);

        AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(Tb2.Result);

        while (!acr.isDone)
        {
            text2.text = (acr.progress * 100).ToString("F2") + "%";
            slider.value = float.Parse((acr.progress ).ToString("F2"));
            yield return null;
        }
        slider.gameObject.SetActive(true);

        ablist = acr.assetBundle;
        AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("MREduastryStart");
        text.text = "正在加载配置";
        while (!abr.isDone)
        {
            text2.text = (abr.progress * 100).ToString("F2") + "%";
            slider.value = float.Parse((abr.progress ).ToString("F2"));
            yield return null;
        }
        Instantiate(abr.asset);

        this.gameObject.SetActive(false);
    }

    IEnumerator DownLoadAssets(bool isRemote=true)
    {


        slider.gameObject.SetActive(true);
        string dllPath = GetWebRequestPath(HotUpdateAllAssets);

        if(isRemote)
        dllPath = GetWebRequestPath();



        Debug.Log($"start download asset:{dllPath}");
        UnityWebRequest www = UnityWebRequest.Get(dllPath);

        www.SendWebRequest();
        while (!www.isDone)
        {
            text2.text = (www.downloadProgress*100).ToString("F2") + "%";
            slider.value = float.Parse((www.downloadProgress ).ToString("F2"));
            yield return null;
        }

#if UNITY_2020_1_OR_NEWER
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
#else
        if (www.isHttpError || www.isNetworkError)
        {
            Debug.Log(www.error);
        }
#endif
        else
        {
            text.text = "正在加载主要资源";
            byte[] assetData = www.downloadHandler.data;


            string fileName = HotUpdateAllAssets;
            if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
                Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");

            string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
            //  if (File.Exists(filePathname))
            //      File.Delete(filePathname);
            File.WriteAllBytes(filePathname, www.downloadHandler.data);
            PlayerPrefs.SetString("HotUpdateAllAssets", filePathname);


            AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(assetData);
            while (!acr.isDone)
            {
                text2.text = (acr.progress * 100).ToString("F2") + "%";
                slider.value = float.Parse((acr.progress ).ToString("F2"));
                yield return null;
            }
            slider.gameObject.SetActive(true);
            ablist = acr.assetBundle;
            AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("MREduastryStart");
            text.text = "正在生成资源";
            while (!abr.isDone)
            {
                text2.text = (abr.progress * 100).ToString("F2") + "%";
                slider.value = float.Parse((abr.progress ).ToString("F2"));
                yield return null;
            }
            Instantiate(abr.asset);

            if (isRemote)
            {
                JsonData data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
                PlayerPrefs.SetString("HotUpdateVersion", data["HotUpdateVersion"].ToString());

            }
            this.gameObject.SetActive(false);

        }
    }


    private static string GetWebRequestPath()
    {
        JsonData data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
        string artUrl = data["HotUpdateAllAssets"].ToString();
        return artUrl;
    }
    private string GetWebRequestPath(string asset)
    {
        var path = $"{Application.streamingAssetsPath}/{asset}";
        if (!path.Contains("://"))
        {
            path = "file://" + path;
        }
        return path;
    }
}