using Intrepid.Gameplay.Entities.Player.Sentinel.Events;
using Intrepid.Gameplay.Messages.Events;
using Intrepid.Structures;
using Intrepid.Utilities;
using UnityEngine;

namespace Intrepid.Gameplay.Entities.Player.Sentinel.StateMachine.States
{
    public class SentinelStateDashImpulse : SentinelState
    {
        [GroupConfigurations, SerializeField] private AnimationClip dash;
        
        private Timer Timer { get; } = new();

        public override bool CanEnterState => SentinelBrain.IsCoreStable;

        public override SentinelStateType GetStateKey()
        {
            return SentinelStateType.DashImpulse;
        }

        protected override void Subscriptions()
        {
            Subscribe<ForceBackOnImpactEvent>(e =>
            {
                Brain.ChangeState(SentinelStateType.Knockdown, 
                    (SentinelConstants.Parameters.KnockdownForce, e.Force));
            });
        }

        protected override void RunOnEnter(ParameterStore parameterStore)
        {
            Brain.Controls.DashCounterInc();
            Brain.Entity.RefreshMovementNormal();
            Brain.Entity.ModelAnimation.CrossFade(dash, 0.05f);
        }

        protected override void RunOnExit()
        {
            Timer.Stop();
        }
        
        public override void RunOnFirstFrameOnly()
        {
            Timer.Start();
        }

        public override void RunOnUpdate()
        {
            Timer.Update(Time.deltaTime);

            Brain.Entity.DesiredVelocity = Brain.Entity.Forward * Brain.Config.DashImpulse.Speed;

            if (!Timer.Check(Brain.Config.DashImpulse.Duration))
            {
                return;
            }

            Timer.Stop();
            Brain.ChangeState(SentinelStateType.DashRecovery);
        }
    }
}