using Microsoft.Xna.Framework;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Attributes;
using Raycast.Win32.Entities;
using System;
using System.Globalization;

namespace Raycast.Win32.Scenes
{
    [Default]
    public class ScaleScene : Scene
    {
        public DrawingSurface GameSurface { get; private set; }
        public SegmentedSkyBox2D SkyBox { get; private set; }

        public Player Player => _scene.Player;

        private NumericLabel _healthLabel;
        private NumericLabel _scoreLabel;
        private TextLabel _text;

        private RenderedScene _scene;

        private Vector2 _smoothedPlayerSpeed;

        public ScaleScene()
        {
            GameSurface = new DrawingSurface(RenderedScene.Size);
            GameSurface.Transformations.Add(ScaleField);
            
            Restart();
        }

        private void OnRestartCommand(object sender, EventArgs e)
        {
            Restart();
        }

        private void Restart()
        {
            MessageCenter.Reset();

            MessageCenter.RestartCommand += OnRestartCommand;

            RemoveAllEntities();

            _scene = GameSurface.NavigateTo<RenderedScene>();

            AddEntity(SkyBox = new SegmentedSkyBox2D(Player, Resources.Textures.Sky, new Point(2048, 512)));
            AddEntity(GameSurface);
            AddEntity(_healthLabel = new NumericLabel { Color = Color.White });
            AddEntity(_scoreLabel = new NumericLabel { Color = Color.White, Position = new Point(4) });
            AddEntity(_text = new TextLabel { Color = Color.Black });
        }

        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);
            _healthLabel.Text = Player.VisibleHealth.ToString(CultureInfo.InvariantCulture);
            _healthLabel.Position = new Point(
                (Configuration.Size.X - _healthLabel.Width) / 2,
                Configuration.Size.Y - _healthLabel.Height - 4);
            _scoreLabel.Text = _scene.KillCount.ToString(CultureInfo.InvariantCulture);
        }

        private void ScaleField(SpriteDrawEventArgs args)
        {
            _smoothedPlayerSpeed = (_smoothedPlayerSpeed * 3 + Player.CurrentSpeed) / 4;

            var offset = new Point((Configuration.Size.X - RenderedScene.Size.X) / 2, (Configuration.Size.Y - RenderedScene.Size.Y) / 2);

            offset.Y += (int)(_smoothedPlayerSpeed.Y * 16);

            args.DestinationRectangle =
                new Rectangle(offset, RenderedScene.Size);
            args.Rotate(
                Player.RotationSpeed / 2 + _smoothedPlayerSpeed.X / 8,
                new Vector2(0.5f));
        }
    }
}