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

namespace AlienAttack.MonoGame.Things.Enemies.Mines;

public abstract class Mine : MoveableSprite
{
    public const int Width = 65;
    public const int Height = 64;

    protected abstract string CoverColor { get; }

    public Mine(int x, int y) : base(x, y)
    {
        Origin = new(30, 33);
        BoundBox = new(10, 14, 40, 38);
        YVelocity = 1;
        XVelocity = 0;
    }

    public override void Draw(SpriteDrawArgs args)
    {
        DrawRotor(args);
        DrawCover(args);
    }

    private void DrawRotor(SpriteDrawArgs args)
    {
        Texture2D texture = args.Content.Load<Texture2D>("Sprites/Rotor");
        args.SpriteBatch.Draw(texture, Position, null, DrawColor, Rotation, Origin, 1f, SpriteEffects.None, 1);
    }

    private void DrawCover(SpriteDrawArgs args)
    {
        Texture2D texture = args.Content.Load<Texture2D>($"Sprites/Cover_{CoverColor}");
        args.SpriteBatch.Draw(texture, Position, null, DrawColor, Rotation, Origin, 1f, SpriteEffects.None, 1);
    }

    public override sealed void Update(SpriteUpdateContext context)
    {
        base.Update(context);

        CollisionBox = new Rectangle((int)XPosition + BoundBox.X - (int)Origin.X, (int)YPosition + BoundBox.Y - (int)Origin.Y, BoundBox.Width, BoundBox.Height);

        float xDiff = (XPosition + Origin.X) - (context.Player.XPosition + context.Player.Origin.X);
        float yDiff = (YPosition + Origin.Y) - (context.Player.YPosition + context.Player.Origin.Y);

        double distance = Math.Sqrt(xDiff * xDiff + yDiff * yDiff);

        if (distance < 100)
        {
            IsDead = true;
            SpawnExplosion(context);
            return;
        }

        if (YPosition - Origin.Y > context.ViewTransform.ScreenHeight)
        {
            IsDead = true;
            return;
        }

        Rotation += 0.01f;

        if (Rotation > 360f)
        {
            Rotation = 0;
        }
    }

    private void SpawnExplosion(SpriteUpdateContext context)
    {
        context.SpawnSprite(new Explosion((int)XPosition, (int)YPosition, XVelocity, YVelocity));
        context.AudioManager.PlayExplosion();
    }
}