using System;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

namespace RebootKit.Engine.Animations {
    [Serializable]
    public class AnimationClipNode : IReAnimatorNode {
        [field: SerializeField] public string Name { get; private set; }

        AnimationClipPlayable m_Playable;

        bool m_PlayOnce;
        Action m_Callback;
        
        public AnimationClip Clip;

        public void Tick(float deltaTime) {
            if (m_Playable.GetPlayState() == PlayState.Paused) {
                return;
            }

            if (m_PlayOnce) {
                if (m_Playable.GetTime() >= m_Playable.GetAnimationClip().length) {
                    m_Playable.Pause();

                    m_Callback?.Invoke();
                    m_Callback = null;

                    m_PlayOnce = false;
                }
            }
        }

        public IPlayable Build(PlayableGraph graph) {
            m_Playable = AnimationClipPlayable.Create(graph, Clip);
            return m_Playable;
        }

        public bool TryFindChild(string name, out IReAnimatorNode node) {
            node = null;
            return false;
        }

        public void PlayOnceWithCallback(Action callback) {
            m_Playable.SetTime(0.0);
            m_Playable.Play();

            m_Callback = callback;
            m_PlayOnce = true;
        }
    }
}