using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class DanMachiAssetLibrary : AssetLibrary
{
    public static DanMachiAssetLibrary Instance => GetInstance<DanMachiAssetLibrary>();

    private List<string> assets = new List<string>();
    private Dictionary<string, string> hashDirectories   = new Dictionary<string, string>();
    private Dictionary<string, string> hashAssets        = new Dictionary<string, string>();
    private Dictionary<string, string> assetHashes       = new Dictionary<string, string>();

    public List<string> CharacterAssets = new List<string>();
    public List<string> AnimationAssets = new List<string>();
    public List<CharacterAsset> Characters = new List<CharacterAsset>();
    public List<CharacterAsset> Animations = new List<CharacterAsset>();

    public CharacterPanel CharacterPanel;

    IEnumerator Start()
    {
        //string assetListUrl = "https://jp-prd-cdn-danmachi-danchro.akamaized.net/resources/assetbundles/catalogs/Android_En/5c8b4dd0ca65f2751ba243ff773db969/catalog_0.0.0.json";
        //yield return Downloader.DownloadText(assetListUrl, str =>
        //{
        //    ParseList(str);
        //});

        string catalogPath      = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "Low\\aiming\\DanChro\\com.unity.addressables\\catalog_0.0.0.json";
        string localFilesPath   = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "Low\\Unity\\aiming_DanChro\\";

        yield return LoadAddressableCatalog(catalogPath);

        //foreach (var dir in Directory.GetDirectories(localFilesPath))
        //{
        //    var fullDir = Directory.GetDirectories(dir)[0];
        //    var hash = fullDir.Split('\\').Last();
        //    hashAssets[hash] = "";
        //    hashDirectories[hash] = fullDir;
        //}

        foreach(var entry in GetAddressableKeys())
        {
            if (entry.StartsWith("chara_") && entry.Contains("assets_all") && !entry.Contains("facial") && !entry.Contains("camanim"))
            {
                if (entry.Contains("_anim_"))
                {
                    AnimationAssets.Add(entry);
                    var chara = new CharacterAsset(entry, localFilesPath + GetResourcePath(entry, out _));
                    Animations.Add(chara);
                }
                else
                {
                    CharacterAssets.Add(entry);
                    var chara = new CharacterAsset(entry, localFilesPath + GetResourcePath(entry, out _));
                    Characters.Add(chara);
                }
            }
        }

        //ParseList(File.ReadAllText(catalogPath));

        //foreach (var asset in CharacterAssets)
        //{
        //    //string assetPath = "https://jp-prd-cdn-danmachi-danchro.akamaized.net/resources/assetbundles/assets/Android_En/" + asset;
        //    //string outPath = Application.dataPath + "/../GameAssets/" + asset;
        //    //if (File.Exists(outPath)) continue;
        //    //yield return Downloader.DownloadAsset(assetPath, outPath, null);
        //    var split = asset.Split(new char[] { '_', '.' });
        //    var hash = split[split.Length - 2];
        //    if (hashAssets.ContainsKey(hash))
        //    {
        //        hashAssets[hash] = asset;
        //        assetHashes[asset] = hash;
        //    }

        //    var filePath = Path.Combine(hashDirectories[hash], "__data");
        //    var chara = new CharacterAsset(asset, filePath);
        //    Characters.Add(chara);
        //}

        DanMachiModelViewerInterface.Instance.CharacterSelection.SetData(Characters);

        yield break;
    }

    //public void ParseList(string assetList)
    //{
    //    var json = JObject.Parse(assetList);
    //    foreach (var entry in json["m_InternalIds"])
    //    {
    //        var fileName = entry.ToString().Split(new char[]{'\\', '/'}).Last();
    //        assets.Add(fileName);
    //        if (fileName.StartsWith("chara_") && fileName.Contains("assets_all") && !fileName.Contains("anim") && !fileName.Contains("facial"))
    //        {
    //            CharacterAssets.Add(fileName);
    //        }
    //        if (fileName.EndsWith(".anim"))
    //        {
    //            Animations.Add(fileName);
    //        }
    //    }
    //}

    public string GetCharacter(string group, string id, string costume)
    {
        return CharacterAssets.First(c => c.StartsWith($"chara_{group}_{id}_{costume}"));
    }
}
