namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Shields Down is an ability that changes Minior's form depending on its HP.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Shields_Down_(Ability)">Bulbapedia - Shields Down</see>
/// </summary>
[Script(ScriptCategory.Ability, "shields_down")]
public class ShieldsDown : 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 != "minior" || pokemon.BattleData?.Battle == null)
            return;
        if (pokemon.CurrentHealth < pokemon.MaxHealth / 2 && pokemon.Form.Name.ToString().EndsWith("-meteor"))
        {
            var coreForm = pokemon.Form.Name.ToString().Replace("-meteor", "");
            if (coreForm == "blue")
                coreForm = "default";
            if (pokemon.Species.TryGetForm(coreForm, out var coreFormData))
            {
                pokemon.ChangeForm(coreFormData);
            }
        }
        else if (pokemon.CurrentHealth >= pokemon.MaxHealth / 2 &&
                 pokemon.Form.Name.ToString().EndsWith("-meteor") == false)
        {
            var baseFormName = pokemon.Form.Name;
            if (baseFormName == "default")
                baseFormName = "blue";
            var meteorFormName = baseFormName + "-meteor";
            if (pokemon.Species.TryGetForm(meteorFormName, out var meteorFormData))
            {
                pokemon.ChangeForm(meteorFormData);
            }
        }
    }
}