namespace PkmnLib.Plugin.Gen7.Scripts.Side;

[Script(ScriptCategory.Side, "doom_desire_effect")]
public class DoomDesireEffect : Script, IScriptOnEndTurn
{
    private class Target
    {
        public byte Position { get; }
        public uint Damage { get; }
        public int Turns { get; set; }

        public Target(byte position, uint damage)
        {
            Position = position;
            Damage = damage;
            Turns = 3;
        }
    }

    private readonly IBattleSide? _side;
    private List<Target> _targets = new();

    public DoomDesireEffect(IBattleSide side)
    {
        _side = side;
    }

    public void AddTarget(byte position, uint damage)
    {
        _targets.Add(new Target(position, damage));
    }

    public bool HasTarget(byte position)
    {
        return _targets.Exists(x => x.Position == position);
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        if (_side == null)
            return;

        var toRemove = new List<Target>();
        foreach (var v in _targets)
        {
            v.Turns--;
            if (v.Turns == 0)
            {
                var pokemon = _side.Pokemon[v.Position];
                pokemon?.Damage(v.Damage, DamageSource.Misc);
                toRemove.Add(v);
            }
        }
        foreach (var v in toRemove)
        {
            _targets.Remove(v);
        }
        if (_targets.Count == 0)
        {
            RemoveSelf();
        }
    }
}