namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Emergency Exit is an ability that makes the Pokémon switch out when its HP drops below half.
/// This ability is similar to Wimp Out and is exclusive to Golisopod.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Emergency_Exit_(Ability)">Bulbapedia - Emergency Exit</see>
/// </summary>
[Script(ScriptCategory.Ability, "emergency_exit")]
public class EmergencyExit : Script, IScriptOnDamage
{
    /// <inheritdoc />
    public void OnDamage(IPokemon pokemon, DamageSource source, uint oldHealth, uint newHealth)
    {
        if (pokemon.BattleData is null)
            return;
        if (source is DamageSource.Confusion)
            return;

        var oldHealthFraction = (float)oldHealth / pokemon.MaxHealth;
        var newHealthFraction = (float)newHealth / pokemon.MaxHealth;
        if (!(oldHealthFraction >= 0.5f) || !(newHealthFraction < 0.5f))
            return;

        if (pokemon.BattleData.Battle.IsWildBattle)
        {
            pokemon.BattleData.Battle.ForceEndBattle();
            return;
        }
        pokemon.BattleData.BattleSide.SwapPokemon(pokemon.BattleData.Position, null);
    }
}