using Microsoft.Xna.Framework;
using MonoGame.FourEngine;

namespace Raycast.Win32.Entities
{
    partial class Enemy
    {
        protected class HurtState : EnemyStateBase
        {
            private const float VerticalAcceleration = 0.015f;

            public Vector2 HurtDirection;
            public float HurtSpeed;

            private float _verticalSpeed;

            public HurtState(Enemy enemy) : base(enemy)
            {
            }

            public override void OnEnter()
            {
                Enemy.Frame = new Point(Enemy.Frame.X, Enemy.AnimationMap[EnemyState.Hurt].Start);

                if (Enemy.VerticalPosition < 0.1f)
                {
                    Enemy.VerticalPosition = Enemy.MinVerticalPosition + 0.1f;
                }

                _verticalSpeed = 0.1f;
            }

            public override void OnUpdate(UpdateEventArgs args)
            {
                if (Enemy.Scene == null) return;

                _verticalSpeed -= VerticalAcceleration;
                Enemy.VerticalPosition += _verticalSpeed;
                if (Enemy.VerticalPosition < Enemy.MinVerticalPosition)
                {
                    Enemy.VerticalPosition = Enemy.MinVerticalPosition;
                    GoToNextState();
                    return;
                }

                if (HurtSpeed > 0)
                {
                    HurtSpeed *= 0.9f;

                    bool CheckMove(float moveX, float moveY)
                    {
                        var vector = new Vector2(moveX, moveY);
                        var point = vector.ToPoint();
                        return Pathfinding.CanPassThrough(point);
                    }

                    var position = Enemy.Position + HurtDirection * HurtSpeed;

                    var diff = position - Enemy.Position;
                    var radius = new Vector2(
                        diff.X > 0 ? Enemy.Radius : -Enemy.Radius, 
                        diff.Y > 0 ? Enemy.Radius : -Enemy.Radius);

                    if (CheckMove(position.X + radius.X, Enemy.Position.Y + Enemy.Radius) &&
                        CheckMove(position.X + radius.X, Enemy.Position.Y - Enemy.Radius))
                        Enemy.Position = new Vector2(position.X, Enemy.Position.Y);

                    if (CheckMove(Enemy.Position.X + Enemy.Radius, position.Y + radius.Y) &&
                        CheckMove(Enemy.Position.X - Enemy.Radius, position.Y + radius.Y))
                        Enemy.Position = new Vector2(Enemy.Position.X, position.Y);
                }
            }
        }
    }
}