using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIKF3MorphSlider : MonoBehaviour
{
    public Slider Slider;
    public UICallbacks ToggleCallbacks;
    public TMPro.TMP_Text Text;
    public Toggle Toggle;

    static KF3ModelViewerInterface UI => KF3ModelViewerInterface.Instance;
    static KF3ModelViewerMain Main => KF3ModelViewerMain.Instance;

    public static UIKF3MorphSlider CreateLookAt(KF3FriendContainer container, Transform parent)
    {
        UIKF3MorphSlider panel = Instantiate(Main.Resources.Pfb_KF3MorphSliderToggle, parent);
        panel.Text.text = "Look At Camera";
        panel.Slider.wholeNumbers = false;
        panel.Slider.minValue = 0;
        panel.Slider.maxValue = 1;
        panel.Slider.value = container.LookAtStrength;
        panel.Slider.onValueChanged.AddListener((value) => { container.UpdateLookAtTarget(value); container.SetKeyframe(); });
        panel.Toggle.isOn = container.EyesLocked;
        panel.Toggle.onValueChanged.AddListener((val) => { container.EyesLocked = val; container.SetKeyframe(); });
        panel.ToggleCallbacks.MouseHover.AddListener(() =>
        {
            panel.ToggleCallbacks.SetTooltipText("Lock current look direction.");
        });
        panel.ToggleCallbacks.MouseHoverEnd.AddListener(() =>
        {
            panel.ToggleCallbacks.SetTooltipText("");
        });
        return panel;
    }

    public static UIKF3MorphSlider CreateMorph(KF3FriendContainer container, SkinnedMeshRenderer meshRenderer, int index, string nameReplace, Transform parent)
    {
        UIKF3MorphSlider panel = Instantiate(Main.Resources.Pfb_KF3MorphSlider, parent);
        
        var helper = new MorphHelper(meshRenderer, meshRenderer.sharedMesh.GetBlendShapeName(index), panel.Slider);
        if (container.Morphs.ContainsKey(meshRenderer))
            container.Morphs[meshRenderer].Add(helper);
        else
            container.Morphs.Add(meshRenderer, new List<MorphHelper>() { helper });

        panel.Text.text = helper.Name.Replace(nameReplace, "");
        panel.Slider.value = meshRenderer.GetBlendShapeWeight(index);
        panel.Slider.onValueChanged.AddListener((value) => {
            helper.UpdateMorph(value);
            container.SetKeyframe();
        });
        return panel;
    }

    public static UIKF3MorphSlider CreateEyeToggle(KF3FriendContainer container, Renderer rend, Transform parent, ToggleGroup group)
    {
        UIKF3MorphSlider panel = Instantiate(Main.Resources.Pfb_KF3MorphToggle, parent);
        panel.Text.text = rend.name;
        panel.Toggle.group = group;
        panel.Toggle.isOn = rend.gameObject.activeSelf;
        panel.Toggle.onValueChanged.AddListener((value) => { container.ToggleVisible(rend.gameObject, value); container.SetKeyframe(); });
        return panel;
    }
}