namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Zen Mode is an ability that changes the Pokémon's form when its HP falls below half.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Zen_Mode_(Ability)">Bulbapedia - Zen Mode</see>
/// </summary>
[Script(ScriptCategory.Ability, "zen_mode")]
public class ZenMode : Script, IScriptOnEndTurn, IScriptOnSwitchIn
{
    /// <inheritdoc />
    public void OnSwitchIn(IPokemon pokemon, byte position) => ChangeFormIfNeeded(pokemon);

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle) => ChangeFormIfNeeded(owner as IPokemon);

    private static void ChangeFormIfNeeded(IPokemon? pokemon)
    {
        if (pokemon is null)
            return;

        if (pokemon.Species.Name != "darmanitan" || pokemon.BattleData?.Battle == null)
            return;
        if (pokemon.CurrentHealth < pokemon.MaxHealth / 2 && pokemon.Form.Name != "zen" &&
            pokemon.Species.TryGetForm("zen", out var zenForm))
        {
            pokemon.ChangeForm(zenForm);
        }
        else if (pokemon.CurrentHealth >= pokemon.MaxHealth / 2 && pokemon.Form.Name == "zen")
        {
            pokemon.ChangeForm(pokemon.Species.GetDefaultForm());
        }
    }
}