using Intrepid.Structures;
using Intrepid.Utilities;
using UnityEngine;

namespace Intrepid.Gameplay.Entities.Player.Sentinel.StateMachine.States
{
    public class SentinelStateDashBreaking : SentinelState
    {
        [GroupConfigurations, SerializeField] private AnimationClip dashBreaking;

        private Timer Timer { get; } = new();
        
        public override SentinelStateType GetStateKey()
        {
            return SentinelStateType.DashBreaking;
        }

        protected override void Subscriptions()
        {
        }

        protected override void RunOnEnter(ParameterStore parameterStore)
        {
            EndCadence();
            Brain.Controls.ResetDash();
            Brain.Entity.ModelAnimation.Play(dashBreaking);
            Timer.Stop();
        }

        protected override void RunOnExit()
        {
            Brain.Entity.DesiredVelocity = Vector2.zero;
            Timer.Stop();
        }

        public override void RunOnUpdate()
        {
            if (Brain.Entity.ModelAnimation.IsFinished)
            {
                if (Timer.IsNotRunning)
                {
                    Brain.Entity.DesiredVelocity = Vector2.zero;
                    Timer.Start();
                    return;
                }
            }
            else
            {
                Brain.Entity.DesiredVelocity = Brain.Entity.Forward * Brain.Config.DashBreaking.Speed;
            }

            if (Timer.IsNotRunning) return;
            Timer.Update(Time.deltaTime);
            var speedCurve = Brain.Config.DashBreaking.SpeedCurve;
            var evaluation = speedCurve.Evaluate((float) Timer.ElapsedTime / Brain.Config.DashBreaking.Duration);
            Brain.Entity.DesiredVelocity = Brain.Entity.Forward * (Brain.Config.DashBreaking.Speed * evaluation);
            if (Timer.Check(Brain.Config.DashBreaking.Duration))
            {
                Timer.Stop();
                Brain.ChangeState(SentinelStateType.Idle);
            }
        }
    }
}