using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEngine;
namespace XenseAR {
public class BlockDataLoader : MonoBehaviour
{
    [SerializeField] DataScriptableObject sessionData;
    [SerializeField] AppSettingObject appSetting;
    public CancellationTokenSource cts;

    public bool needDownloadData = false;
    void Start()
    {
        cts = new CancellationTokenSource();
    }
    private void OnDestroy()
    {
        cts?.Cancel();
    }


    int count = 0;
    int anchoringLen = 1;

    public void RequestDownloadWorldData(List<AnchoringTarget> downloadList)
    {
        Debug.Log("RequestDownloadWorldData");
        count = 0;
        DownloadWorldData(downloadList);
    }

    public async void DownloadWorldData(List<AnchoringTarget> targets)
    {
        InvokeRepeating("UpdateDownloadProgress", 0f, 0.5f);
        count = 0;
        List<AnchoringTarget> needLoadTargets = targets;

        anchoringLen = needLoadTargets.Count;
        Debug.Log("Content need download: " + anchoringLen);
        foreach (var target in needLoadTargets)
        {
            Debug.Log("Download: " + target.media.url);
            switch (target.media.Type)
            {
                case AnchoringMediaType.Gltf:
                    GltfCacher gltfCacher = new GltfCacher();
                    gltfCacher.DownloadAndCache(target.media.url, null, null, null, null, cts.Token, OnDownLoadGltfFinish);
                    break;
                case AnchoringMediaType.Image:
                    Davinci.get().load(target.media.url).setCached(true).withDownloadedAction((path) =>
                    {
                        count++;
                    }).start();
                    break;
                case AnchoringMediaType.Assetbundle:
                    AssetBundleLoader loader = new AssetBundleLoader(this, target.media.url, target.media.name);
                    loader.LoadAsync(null, false, OnloadBundleFinish);
                    break;
            }

        }
        UpdateDownloadProgress();

    }

    bool needDownloadWorldData = false;
 

    void UpdateDownloadProgress()
    {
        if(anchoringLen == 0)
        {
            API.UpdateAnchoringDownloadProgress(((int)100).ToString());
            CancelInvoke("UpdateDownloadProgress");
                return;
        }
        double progress = (double)count / anchoringLen * 100;

        Debug.Log("progress update " + progress.ToString() + "; " + count +"/" + anchoringLen);
        API.UpdateAnchoringDownloadProgress(((int)progress).ToString());

        if (count >= anchoringLen) CancelInvoke("UpdateDownloadProgress");
    }

    private void OnloadBundleFinish()
    {
        count++;
    }

    private void OnDownLoadGltfFinish()
    {
        count++;
    }

    public void StopDownloadWorldData()
    {
        CancelInvoke("UpdateDownloadProgress");
        cts?.Cancel();
    }
}
}
