using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace AlienAttack.MonoGame.Things;

public class Sprite(float x, float y)
{
    public float XPosition { get; protected set; } = x;
    public float YPosition { get; protected set; } = y;
    public Vector2 Position => new(XPosition, YPosition);
    public float Rotation { get; protected set; }
    public Vector2 Origin { get; protected set; }
    public Vector2 Scale { get; protected set; } = new(1, 1);
    public Rectangle BoundBox { get; protected set; }

    protected Rectangle CollisionBox;
    protected Color DrawColor = Color.White;

    public bool CanCollide { get; protected set; } = true;
    public bool IsDead { get; protected set; }

    public virtual void Update(SpriteUpdateContext context)
    {
        //CollisionBox = new Rectangle((int)XPosition + BoundBox.X, (int)YPosition + BoundBox.Y, BoundBox.Width, BoundBox.Height);
        CollisionBox = new Rectangle((int)(Position.X - Origin.X) + BoundBox.X, (int)(Position.Y - Origin.Y) + BoundBox.Y, BoundBox.Width, BoundBox.Height);
    }

    public bool Intersects(Sprite sprite)
    {
        return CollisionBox.Intersects(sprite.CollisionBox);
    }

    public virtual void Draw(SpriteDrawArgs args)
    {
        //spriteBatch.Draw(Texture, Position, DrawColor);

        if (args.ShowCollisionBox)
        {
            DrawCollisionBox(args);
        }
    }

    private void DrawCollisionBox(SpriteDrawArgs args)
    {
        //var pixel = DebugPixel; // static cached

        Texture2D pixel = new Texture2D(args.SpriteBatch.GraphicsDevice, 1, 1);
        pixel.SetData(new[] { Color.White });

        //Rectangle r = GetWorldCollisionBox();

        Color c = Color.LimeGreen; // debug color

        // Top
        args.SpriteBatch.Draw(pixel, new Rectangle(CollisionBox.X, CollisionBox.Y, CollisionBox.Width, 1), c);
        // Bottom
        args.SpriteBatch.Draw(pixel, new Rectangle(CollisionBox.X, CollisionBox.Bottom - 1, CollisionBox.Width, 1), c);
        // Left
        args.SpriteBatch.Draw(pixel, new Rectangle(CollisionBox.X, CollisionBox.Y, 1, CollisionBox.Height), c);
        // Right
        args.SpriteBatch.Draw(pixel, new Rectangle(CollisionBox.Right - 1, CollisionBox.Y, 1, CollisionBox.Height), c);
    }

    public virtual void OnCollision(SpriteCollisionContext context)
    {

    }
}