using System.Linq;
using UnityEngine;
using System.Collections;
using Newtonsoft.Json.Linq;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using System.Collections.Generic;

public class AssetLibrary : MonoBehaviour
{
    protected static AssetLibrary _mainInstance;
    public ResourceLocationMap AddressableResourceMap;
    private List<string> _addressableKeys;
    public string LocalFilesPath;

    public static T GetInstance<T>() where T : AssetLibrary
    {
        return _mainInstance as T;
    }

    public List<string> GetAddressableKeys()
    {
        if (_addressableKeys == null)
        {
            _addressableKeys = AddressableResourceMap.Keys.Select(k=>k.ToString()).ToList();
        }
        return _addressableKeys.ToList();
    }

    /// <summary>
    /// Load catalog.json from games that use addressables
    /// </summary>
    /// <param name="catalogPath"></param>
    /// <returns></returns>
    public IEnumerator LoadAddressableCatalog(string catalogPath)
    {
        var opHandle = Addressables.LoadContentCatalogAsync(catalogPath);
        yield return opHandle;

        if (opHandle.Status == AsyncOperationStatus.Succeeded)
        {
            Debug.Log(opHandle.Result.GetType());
            AddressableResourceMap = opHandle.Result as ResourceLocationMap;
        }
        else
        {
            throw opHandle.OperationException;
        }

        //var keys = AddressableResourceMap.Keys.Where(k=>k.ToString().Contains("chara_100_0001")).ToList();
        //for (int i = 0; i < keys.Count; i++)
        //{
        //    Debug.Log(keys[i].ToString());
        //    Debug.Log(JObject.FromObject(AddressableResourceMap.Locations[keys[i]][0]).ToString());
        //    Debug.Log(AddressableResourceMap.Locations[keys[i]][0].Data.GetType());
        //    //switch (AddressableResourceMap.Locations[keys[i]][0])
        //    //{
        //    //    case CompactLocation cl:
        //    //        break;
        //    //}
        //}
    }

    public string GetResourcePath(string resourceName)
    {
        var locator = AddressableResourceMap.Locations[resourceName][0]; // AddressableResourceMap.Locations[resourceName][0].Dependencies[0].Data as AssetBundleRequestOptions;
        if (locator.HasDependencies)
        {
            return "";
        }
        var data = locator.Data as AssetBundleRequestOptions;
        var filePath = data.BundleName + "/" + data.Hash + "/" + "__data";
        return filePath;
    }
}