using Microsoft.Xna.Framework;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Raycast;
using Raycast.Win32.Entities;
using Raycast.Win32.Services;
using static MonoGame.FourEngine.ServiceLocator;

namespace Raycast.Win32.Components
{
    public class ShooterComponent : RaycastComponent
    {
        private const float DoorOpeningSpeed = 0.1f;

        public Player Player { get; }

        public Point? OpeningDoor { get; set; }

        private IPathfindingService Pathfinding => LazyResolver<IPathfindingService>.Resolve();

        public ShooterComponent(IRaycastMap map, Scene scene, IRaycastCamera camera, Point resolution) 
            : base(map, scene, camera, resolution)
        {
            Pathfinding.Map = map;
            Player = (Player)camera;
            Player.InitAutoAim(resolution.X);
        }

        protected override void OnBeginCast()
        {
            Player.ResetAutoAim();
        }

        protected override void OnCastedObject(IRaycastObject obj, Rectangle destinationRect, int i)
        {
            if (obj is Enemy enemy)
                Player.OnPossibleAutoAimPretendent(enemy, destinationRect, WallLayers[0]);
        }
        
        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);

            if (OpeningDoor.HasValue)
            {
                if (TextureOffsets[OpeningDoor.Value.X, OpeningDoor.Value.Y] < 1)
                {
                    TextureOffsets[OpeningDoor.Value.X, OpeningDoor.Value.Y] += DoorOpeningSpeed;
                }
                else
                {
                    Pathfinding.Unblock(OpeningDoor.Value);
                    Map.Layers[0].Data[OpeningDoor.Value.X, OpeningDoor.Value.Y] = 0;
                    OpeningDoor = null;
                }
                ForceRedraw();
            }
        }
    }
}
