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

namespace Raycast.Win32.Entities
{
    partial class Enemy
    {
        protected class ShootState : EnemyStateBase
        {
            public const float ShootLength = 10f;

            protected const double MsShoot = 600d;
            protected const double MsNext = 1200d;

            private static readonly Random Random = new Random(DateTime.UtcNow.Millisecond);

            private double _msPassed;

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

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

                _msPassed = 0;

                Enemy.OnAttack();

                var direction = Enemy.Scene.Player.Position - Enemy.Position;
                direction.Normalize();
                Enemy.Orientation = direction.OrientTo();
                Enemy.Direction = direction;
            }

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

                Enemy.VerticalPosition = Enemy.MinVerticalPosition;
                
                var msPassed = _msPassed + args.DeltaTime.TotalMilliseconds;

                if (_msPassed < MsShoot && msPassed >= MsShoot)
                {
                    var projectile1 = RecyclePool<EnemyProjectile>.Get();
                    projectile1.Position = Enemy.Position;
                    projectile1.Direction = Enemy.Direction;
                    Enemy.Scene.AddEntity(projectile1);

                    var projectile2 = RecyclePool<EnemyProjectile>.Get();
                    var randomDirection = new Vector2(
                        (float)(Random.NextDouble() - 0.5d),
                        (float)(Random.NextDouble() - 0.5d));
                    randomDirection.Normalize();
                    projectile2.Position = Enemy.Position;
                    projectile2.Direction = randomDirection;
                    Enemy.Scene.AddEntity(projectile2);
                }

                if (msPassed >= MsNext)
                {
                    GoToNextState();
                }

                _msPassed = msPassed;
            }
        }
    }
}