using System;
using System.Linq;
using UnityEngine;

public class CharacterPanel : MonoBehaviour
{
    public ExtendedDropdown AnimationSetDropdown;
    public ExtendedDropdown AnimationDropdown;
    public ExtendedDropdown CostumeDropdown;
    private DanMachiCharacterContainer _selectedChara;

    public static CharacterPanel Create(DanMachiCharacterContainer chara)
    {
        var panel = Instantiate(DanMachiAssetLibrary.Instance.CharacterPanel, ModelViewerInterface.GetInstance().DynamicPanels.transform);
        panel.Init(chara);
        return panel;
    }

    public void Init(DanMachiCharacterContainer chara)
    {
        _selectedChara = chara;
        CostumeDropdown.SetOptions(DanMachiAssetLibrary.Instance.Characters.Where(a => a.Category == chara.Data.Category && a.Id == chara.Data.Id).Select(a => a.Costume).ToList());
        CostumeDropdown.SetValueWithoutNotify(chara.Data.Costume);
        AnimationSetDropdown.SetOptions(DanMachiAssetLibrary.Instance.Animations.Where(a => a.Category == chara.Data.Category && a.Id == chara.Data.Id).Select(a => a.Costume).ToList(), true);
    }

    public void SelectCostume(int value)
    {
        var pose = _selectedChara.SerializeFrame();
        var data = _selectedChara.Data;
        var newData = DanMachiAssetLibrary.Instance.Characters.First(c => c.Category == data.Category && c.Id == data.Id && c.Costume == CostumeDropdown.options[value].text);
        var chara = DanMachiModelBuilder.Instance.SpawnCharacter(newData);
        chara.PastePose(pose, PoseLoadOptions.All());
    }

    public void SelectAnimationSet(int value)
    {
        if(value == 0)
        {
            AnimationDropdown.SetOptions(null);
            return;
        }
        var data = _selectedChara.Data;
        var animSet = DanMachiAssetLibrary.Instance.Animations.First(a => a.Category == data.Category && a.Id == data.Id && a.Costume == AnimationSetDropdown.options[value].text);

        _selectedChara.LoadAnimationSet(animSet);

        AnimationDropdown.SetOptions(_selectedChara.Animations.Select(a=>a.name).ToList(), true);
    }

    public void SelectAnimation(int value)
    {
        if (value == 0)
        {
            _selectedChara.PlayAnimation((AnimationClip)null);
            return;
        }
        else
        {
            _selectedChara.PlayAnimation(_selectedChara.Animations[value-1]);
        }
    }
}
