using System;
using Microsoft.Xna.Framework;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Entities;
using MonoGame.FourEngine.Raycast.Tiled;
using MonoGame.FourEngine.Resources;
using Raycast.Win32.Entities;

namespace Raycast.Win32.Scenes
{
    public class RenderedScene : Scene
    {
        public static readonly Point Size = Configuration.Size + new Point(100);

        public RaycastTiledMap Map { get; }
        public ShooterViewEntity View { get; }

        public int KillCount { get; private set; }

        public Player Player => View.Component.Player;

        private ColoredRectangle _redOverlay;

        private float _overlayOpacity;

        public RenderedScene()
        {
            // Enough for now?
            RecyclePool<Smoke>.Init(200);
            RecyclePool<Rocket>.Init(100);
            RecyclePool<BloodSplash>.Init(100);
            RecyclePool<Explosion>.Init(100);
            RecyclePool<EnemyProjectile>.Init(50);

            _redOverlay = new ColoredRectangle(Color.Red);

            AddEntity(View = new ShooterViewEntity(
                Map = new RaycastTiledMap(this, Resources.Maps.Demo),
                Map.Camera,
                Size));
            AddEntity(new PlayerGun(Player));
            var music = new MusicEntity();
            music.Play(Resources.Music.Game);
            AddEntity(music);

            MessageCenter.PlayerHurt += OnPlayerHurt;
            MessageCenter.EnemyDead += OnEnemyDead;
        }

        private void OnPlayerHurt(object sender, int damage)
        {
            _overlayOpacity += damage / 10f;
        }

        private void OnEnemyDead(object sender, EventArgs e)
        {
            KillCount++;
        }

        public override void OnUpdate(UpdateEventArgs args)
        {
            if (Player.Health > 0 || _overlayOpacity > 0.5f)
                _overlayOpacity /= 1.1f;
            base.OnUpdate(args);
        }

        public override void OnDraw(DrawEventArgs args)
        {
            base.OnDraw(args);

            if (DrawingSurface != null)
            {
                args.Batch.Draw(_redOverlay, new Rectangle(0, 0, DrawingSurface.Width, DrawingSurface.Height), Color.White * _overlayOpacity);
            }
        }
    }
}