using System;
using Microsoft.Xna.Framework;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Components;
using MonoGame.FourEngine.Raycast;
using MonoGame.FourEngine.Resources;

namespace Raycast.Win32.Entities
{
    public class PlaneSkyBox2D : Entity
    {
        private IRaycastCamera _camera;

        private SpriteComponent _spriteCopy1;
        private SpriteComponent _spriteCopy2;

        public PlaneSkyBox2D(IRaycastCamera camera, SpriteDefinition spriteDefinition)
        {
            _camera = camera;
            Components.Add(_spriteCopy1 = new SpriteComponent(spriteDefinition));
            Components.Add(_spriteCopy2 = new SpriteComponent(spriteDefinition));
            Components.Add(new ActionComponent(OnUpdate));
        }

        public PlaneSkyBox2D(IRaycastCamera camera, string fileName, Point size) 
            : this(
                camera, 
                new SpriteDefinition
                {
                    FileName = fileName,
                    Size = size
                })
        { }

        private void OnUpdate(UpdateEventArgs args)
        {
            var angle = Math.PI + Math.Atan2(_camera.Direction.Y, _camera.Direction.X);
            var percent = angle / (Math.PI * 2);

            _spriteCopy1.Position = new Point((int)(_spriteCopy1.Sprite.Size.X * percent), 0);
            _spriteCopy2.Position = new Point(_spriteCopy1.Position.X - _spriteCopy1.Sprite.Size.X, 0);
        }
    }
}