using Microsoft.Xna.Framework;
using System.Linq;

namespace Igdc.Scenes
{
    public partial class BattleScene
    {
        protected override void Draw(SceneIterationArgument e)
        {
            e.Batch.Draw(_background, Vector2.Zero, Color.White);

            DrawOverlay(e, 0, 34);
            DrawHealthBar(e);
            DrawEnemies(e, 0);
            DrawOverlay(e, 34, 29);
            DrawEnemies(e, 1);
            DrawOverlay(e, 63, 81);

            DrawBullets(e);
            DrawPlayer(e);
        }

        private void DrawOverlay(SceneIterationArgument e, int start, int end)
        {
            var rect = new Rectangle(0, start, e.ScreenSize.X, end);
            e.Batch.Draw(_overlay, rect, rect, Color.White);
        }

        private void DrawEnemies(SceneIterationArgument e, int y)
        {
            foreach (var enemy in _enemies.Where(q => q.Y == y))
            {
                var enemyLocation = new Point(15 + 50 * enemy.X, 16 + 29 * enemy.Y);
                var animationFrame = enemy.GetAnimationFrame();
                var source = new Point(animationFrame.X * enemy.Size.X, animationFrame.Y * enemy.Size.Y);
                e.Batch.Draw(_enemyTextures[enemy.Texture], 
                    new Rectangle(enemyLocation, enemy.Size), 
                    new Rectangle(source, enemy.Size),
                    enemy.Color);
            }
        }

        private void DrawBullets(SceneIterationArgument e)
        {
            foreach (var bullet in _bullets)
            {
                var bulletLocation = new Point(25 + 50 * bullet.X, 27 + 30 * bullet.Y + bullet.Offset.Y);
                e.Batch.Draw(_projectile, new Rectangle(bulletLocation, bullet.Size), bullet.Color);
            }
        }

        private void DrawPlayer(SceneIterationArgument e)
        {
            var playerLocation = _player.Interpolate(new Point(7 + 49 * _player.X, 86));
            var animationFrame = _player.GetAnimationFrame();
            var source = new Point(animationFrame.X * _player.Size.X, animationFrame.Y * _player.Size.Y);
            e.Batch.Draw(_playerTexture,
                new Rectangle(playerLocation, _player.Size),
                new Rectangle(source, _player.Size),
                Color.White);
        }

        private void DrawHealthBar(SceneIterationArgument e)
        {
            foreach (var element in _player.HealthBar)
            {
                var elementLocation = new Point(100 + 20 * element.X, 1);
                var animationFrame = element.GetAnimationFrame();
                var source = new Point(animationFrame.X * element.Size.X, animationFrame.Y * element.Size.Y);
                e.Batch.Draw(_healthBarElement, 
                    new Rectangle(elementLocation, element.Size), 
                    new Rectangle(source, element.Size), 
                    Color.White);
            }
        }
    }
}