using LeMangeurDEnfants.Core.Scenes;
using Microsoft.Xna.Framework;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Extensions;
using System;
using System.Linq;

namespace LeMangeurDEnfants.Core.Entities
{
    public class ButtonPlate : BaseObject
    {
        public override string FileName => Resources.Sprites.ButtonPlate;
        public override Point Size => new Point(16);

        public int Kind
        {
            get => _kind;
            set
            {
                _kind = value;
                Frame = new Point(Frame.X, value);
            }
        }
        private int _kind;

        private bool _isPressed;

        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);
            SpriteComponent.Layer = 1;
            if (!_isPressed && Scene is GameScene gameScene && gameScene.BigBoss != null)
            {
                CheckCollision(gameScene);
            }
        }

        private void CheckCollision(GameScene scene)
        {
            if (Collide(scene.BigBoss.Position))
            {
                _isPressed = true;
                Frame = new Point(1, Frame.Y);
                var gates = scene
                    .Entities
                    .Filter<Gate>()
                    .Where(x => x.Kind == Kind)
                    .ToList();
                foreach (var gate in gates)
                {
                    scene.RemoveEntity(gate);
                }
                scene.BigBoss.OpenSfx.Play();
            }
        }

        public override bool Collide(Point center)
        {
            var diff = Position - center;
            return Math.Abs(diff.X) <= Size.X && Math.Abs(diff.Y) <= Size.Y;
        }
    }
}