using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class DanMachiModelBuilder : ModelBuilder
{
    public static DanMachiModelBuilder Instance => GetInstance<DanMachiModelBuilder>();

    public override IEnumerator SpawnSerializedCoroutine(ObjectContainerSerializable oc, Action<ObjectContainer> callback = null)
    {
        yield return base.SpawnSerializedCoroutine(oc);

        switch (oc)
        {
            case DanMachiCharacterSerializable character:
                {
                    var chara = SpawnAsset(AssetTypes.Character, character.AssetName);
                    chara.DeserializeFrames(character);
                    break;
                }
            default:
                {
                    Error.Log(Color.red, "Data not recognized: " + oc.Filename + " " + oc.GUID);
                    break;
                }
        }
        yield break;
    }

    public override ObjectContainer SpawnAsset(Enum assetType, string assetPath)
    {
        base.SpawnAsset(assetType, assetPath);

        switch (assetType)
        {
            case AssetTypes.Unknown:
                throw new NotImplementedException();
            case AssetTypes.Character:
                var asset = DanMachiAssetLibrary.Instance.Characters.First(c=>c.AssetName == assetPath);
                return SpawnCharacter(asset);
            default:
                throw new NotImplementedException();
        }
    }

    private DanMachiCharacterContainer SpawnCharacter(CharacterAsset asset)
    {
        var container = ObjectContainer.Create<DanMachiCharacterContainer>("Character");
        var handle = UIHandle.CreateAsChild<UIHandleMain>(container.transform).Init(container);
        container.Build(asset);

        var animationSets = DanMachiAssetLibrary.Instance.Animations.Where(a => a.Category == asset.Category && a.Id == asset.Id);
        var defaultAnimSet = animationSets.FirstOrDefault(a => a.Costume == "common");
        defaultAnimSet ??= animationSets.FirstOrDefault();
        if (defaultAnimSet != null)
        {
            var animSetDropdown = container.CharacterPanel.AnimationSetDropdown;
            var option = animSetDropdown.options.FindIndex(d => d.text == defaultAnimSet.Costume);
            if (option != -1)
            {
                animSetDropdown.value = option;
                container.CharacterPanel.AnimationDropdown.value = 1;
            }
        }

        DanMachiMain.Instance.SelectObject(container);

        return container;
    }
}