using ET;
using Animancer;
using UnityEngine;
using System;

namespace Mono
{
    public class AnimationData : MonoBehaviour
    {
        public AnimancerComponent Animancer;
        public enum AnimationType
        {
            Idle,
            Run,
            Dead,
            Damage,
            Skill0,
            Skill1,
            Skill2,
            Skill3,
            Skill4,
            Skill5,
            Skill6,

            SkillMax
        }

        [Serializable]
        public struct AniInfo
        {
            public AnimationType Type;
            public ClipTransition Clip;
        }

        public AniInfo[] AnimationClips = new AniInfo[1];
        private Action aniEndcb;
        private AnimancerState notifyState;

        public bool IsPauseStatus() { return !Animancer.Playable.IsGraphPlaying; }

        private void Awake ()
        {
            aniEndcb = null;
            foreach (var clip in AnimationClips)
            {
                if (clip.Type >= AnimationType.Skill0 && clip.Type < AnimationType.SkillMax)
                {
                    clip.Clip.Events.OnEnd = SkillEndCB;
                }
            }
        }

        protected void SkillEndCB()
        {
            if(notifyState != null /*&& notifyState.IsPlaying*/)
            {
                notifyState.Events = null;
                notifyState = null;
            }
            Action tocall = aniEndcb;
            aniEndcb = null;
            tocall?.Invoke();
        }

        public ClipTransition GetClip(AnimationType type)
        {
            foreach (var clip in AnimationClips)
            {
                if (clip.Type == type)
                {
                    return clip.Clip;
                }
            }
            return null;
        }

        public void PlayAnimation(AnimationType type, Action endcb = null)
        {
            if (!Animancer.Playable.IsGraphPlaying)
            {
                //Log.Error( $"play ani({type}) @ froze status" );
                return;
            }
            //Log.Debug($"{this.gameObject.name} toplay ani:{type}");
            aniEndcb = endcb;
            var clip = GetClip(type);
            if (clip != null)
            {
                notifyState = Animancer.Play(clip, 0.1f, FadeMode.FromStart);
            }
            else
            {
                Log.Error($"Not exist clip({type}) @{gameObject.name}");
            }
        }

        public void Pause()
        {
            Animancer.Playable.PauseGraph();
        }
        public void Resume()
        {
            Animancer.Playable.UnpauseGraph();
        }
    }
}