namespace PkmnLib.Plugin.Gen7.Scripts.Battle;

[Script(ScriptCategory.Battle, "gravity")]
public class Gravity : Script, IScriptFailIncomingMove, IScriptOnEndTurn, IScriptChangeTypesForIncomingMove,
    IScriptIsFloating
{
    private int _turns = 5;

    /// <inheritdoc />
    public void ChangeTypesForIncomingMove(IExecutingMove executingMove, IPokemon target, byte hitIndex,
        IList<TypeIdentifier> types)
    {
        var typeLibrary = target.Library.StaticLibrary.Types;

        if (executingMove.UseMove.MoveType.Name != "ground")
            return;
        // Remove all types that are immune to ground moves
        types.RemoveAll(x => typeLibrary.GetSingleEffectiveness(executingMove.UseMove.MoveType, x) == 0);
    }

    /// <inheritdoc />
    public void FailIncomingMove(IExecutingMove move, IPokemon target, ref bool fail)
    {
        if (move.UseMove.HasFlag(MoveFlags.Gravity))
            fail = true;
    }

    /// <inheritdoc />
    public void IsFloating(IPokemon pokemon, ref bool isFloating)
    {
        // Gravity makes all Pokémon susceptible to Ground-type moves
        isFloating = false;
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        _turns--;
        if (_turns > 0)
            return;

        RemoveSelf();
    }
}