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

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

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

    public List<CharacterAsset> Characters;

    IEnumerator Start()
    {
        var selectedFilePath = new string[0];
        var catalogPath = ModelViewerSettings.Get("CatalogPath", new ModelViewerSettings.Setting("", ModelViewerSettings.SettingType.FilePath));
        var assetsPath = ModelViewerSettings.Get("AssetsPath", new ModelViewerSettings.Setting("", ModelViewerSettings.SettingType.FolderPath));

        if (!File.Exists(catalogPath))
        {
            selectedFilePath = new string[0];
            while (true)
            {
                selectedFilePath = StandaloneFileBrowser.OpenFilePanel("Select catalog_eversoul.json", catalogPath, "json", false);
                if (selectedFilePath.Length > 0 && !string.IsNullOrEmpty(selectedFilePath[0]))
                {
                    break;
                }
                yield return new WaitForSeconds(5);
            }
            catalogPath = selectedFilePath[0];
            ModelViewerSettings.Set("CatalogPath", catalogPath);
        }

        if (!Directory.Exists(assetsPath))
        {
            selectedFilePath = new string[0];
            while (true)
            {
                selectedFilePath = StandaloneFileBrowser.OpenFolderPanel("Select folder with converted assets", assetsPath, false);
                if (selectedFilePath.Length > 0 && !string.IsNullOrEmpty(selectedFilePath[0]))
                {
                    break;
                }
                yield return new WaitForSeconds(5);
            }
            assetsPath = selectedFilePath[0] + "\\";
            ModelViewerSettings.Set("AssetsPath", assetsPath);
        }

        ModelViewerSettings.Save();

        yield return LoadAddressableCatalog(catalogPath);

        var keys = GetAddressableKeys();
        var charas = keys.Where(k => k.Contains("Character") && k.Contains("/Prefabs/") && k.EndsWith(".prefab")).ToList();

        foreach(var chara in charas)
        {
            Characters.Add(new CharacterAsset(chara));
        }

        CharacterAssets = charas;

        EversoulInterface.Instance.CharacterSelection.SetData(Characters);

        yield break;
    }
}
