using AlienAttack.MonoGame.Textures;
using AlienAttack.MonoGame.Things.Items;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace AlienAttack.MonoGame.Things.Bullets;

public abstract class Bullet : MoveableSprite
{
    public Sprite Owner { get; init; }
    public int Damage { get; init; } = 0;

    protected abstract string TextureName { get; }

    public Bullet(float x, float y, float xVel, float yVel, Sprite owner) : base(x, y)
    {
        XVelocity = xVel;
        YVelocity = yVel;
        Owner = owner;
    }

    public override void Draw(SpriteDrawArgs args)
    {
        Texture2D texture = args.Textures.Get(TextureName);

        args.SpriteBatch.Draw(texture, Position, null, DrawColor, Rotation, Origin, Scale, SpriteEffects.None, 1);
    }

    public override void Update(SpriteUpdateContext context)
    {
        Rotation = MathF.Atan2(YVelocity, XVelocity) + MathF.PI / 2f;

        if (XPosition + BoundBox.Width < 0
            || XPosition > context.ViewTransform.ScreenWidth
            || YPosition + BoundBox.Height < 0
            || YPosition > context.ViewTransform.ScreenHeight)
        {
            IsDead = true;
        }

        base.Update(context);
    }

    public override void OnCollision(SpriteCollisionContext context)
    {
        Sprite sprite = context.Sprite;

        if (sprite is Bullet || sprite == Owner || sprite is Item || sprite is Explosion)
            return;

        IsDead = true;

        float xVel = 0;
        float yVel = 0;

        if (context.Sprite is MoveableSprite moveableSprite)
        {
            xVel = moveableSprite.XVelocity;
            yVel = moveableSprite.YVelocity;
        }

        context.SpawnSprite(new MiniExplosion((int)XPosition, (int)YPosition, xVel, yVel));

        context.AudioManager.PlayImpact();
    }
}