using Spine;
using Spine.Unity;
using System;
using XGame.Framework.Components;
using XGame.Framework.Time;

namespace FL.Battle
{
    public enum ActionName
    {
        idle = 0,
        attack,
    }
    public interface ISpineContext
    {
        SkeletonAnimation Skeleton { get; }
        ITimeModule Time { get; }
    }
    public class SpineComponent : Component<ISpineContext>
    {
        private ITimer _actionTimer;
        public override int Order => 0;

        protected override void OnDispose()
        {
            _actionTimer?.Cancel();
            _actionTimer = null;
        }
        public bool IsLoop(ActionName actionName)
        {
            switch (actionName)
            {
                case ActionName.idle:
                    return true;
                default: 
                    return false;
            }
        }
        public void Play(ActionName actionName, Action callback = null)
        {
            var skeleton = Context.Skeleton;
            if (skeleton == null)
                return;
            var isLoop = IsLoop(actionName);
            skeleton.loop = isLoop;
            skeleton.AnimationName = actionName.ToString();
            //var state = skeleton.AnimationState;
            //state.Tracks.Items[0].Animation.Duration
            _actionTimer?.Cancel();
            if (!isLoop)
            { // 非循环动作才有回调
                _actionTimer = Context.Time.AddDelayTimer(833, () =>
                {
                    _actionTimer = null;
                    callback?.Invoke();
                });
            }
            //state.Complete += (_) =>
            //{
            //    callback?.Invoke();
            //};
        }
        private void OnCompleted(TrackEntry trackEntry)
        {

        }
    }
}
