using Spine.Unity;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class PlayClickAnimation : MonoBehaviour
{
    private readonly string ClickAnimation = "click";
    private readonly string IdleAnimation = "idle";
    private readonly string StartAnimationName = "start";

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Start");
        var skeletonGraphics = gameObject.GetComponentsInChildren<SkeletonGraphic>();
        foreach (var skeletonGraphic in skeletonGraphics)
        {
            var startAnimation = skeletonGraphic.skeletonDataAsset.GetSkeletonData(false).FindAnimation(StartAnimationName);
            var idleAnimation = skeletonGraphic.skeletonDataAsset.GetSkeletonData(false).FindAnimation(IdleAnimation);
            var clickAnimation = skeletonGraphic.skeletonDataAsset.GetSkeletonData(false).FindAnimation(ClickAnimation);
            if (startAnimation != null) {
                skeletonGraphic.AnimationState.SetAnimation(0, startAnimation, false);
                if (idleAnimation != null) {
                    skeletonGraphic.AnimationState.AddAnimation(0, idleAnimation, true, 0);
        
                }
            }else if (idleAnimation != null) {
                skeletonGraphic.AnimationState.SetAnimation(0, idleAnimation, true);
            }

            if (clickAnimation != null){
                EventTrigger.Entry entry = new EventTrigger.Entry();
                EventTrigger.TriggerEvent trigger = new EventTrigger.TriggerEvent();
                entry.eventID = EventTriggerType.PointerClick;
                entry.callback = trigger;
                trigger.AddListener((BaseEventData eventData) => {
                    Debug.Log("OnClick");
                    skeletonGraphic.AnimationState.SetAnimation(0, ClickAnimation, false);
                    skeletonGraphic.AnimationState.AddAnimation(0, IdleAnimation, true, 0);
                });
                EventTrigger triggerCom = skeletonGraphic.gameObject.GetComponent<EventTrigger>();
                if (triggerCom == null)
                {
                    triggerCom = skeletonGraphic.gameObject.AddComponent<EventTrigger>();
                }
                triggerCom.triggers.Add(entry);
            }
        }
        
    }
}
