namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Flower Gift is an ability that boosts the Attack and Special Defense of the Pokémon and its allies in sunlight.
/// This ability is exclusive to Cherrim.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Flower_Gift_(Ability)">Bulbapedia - Flower Gift</see>
/// </summary>
[Script(ScriptCategory.Ability, "flower_gift")]
public class FlowerGift : Script, IScriptOnWeatherChange
{
    private IPokemon? _pokemon;

    /// <inheritdoc />
    public override void OnAddedToParent(IScriptSource source)
    {
        if (source is not IPokemon pokemon)
            throw new InvalidOperationException("Flower Gift can only be added to a Pokemon script source.");
        _pokemon = pokemon;
        var effect = _pokemon.BattleData?.BattleSide.VolatileScripts.Add(new Side.FlowerGiftEffect());
        (effect?.Script as Side.FlowerGiftEffect)?.OnAdded(_pokemon);
    }

    /// <inheritdoc />
    public void OnWeatherChange(IBattle battle, StringKey? weatherName, StringKey? oldWeatherName)
    {
        if (_pokemon is null)
            return;
        if (weatherName != ScriptUtils.ResolveName<Weather.HarshSunlight>())
            return;
        if (_pokemon.Species.Name != "cherrim")
            return;
        EventBatchId batchId = new();
        if (_pokemon.Species.TryGetForm("sunshine", out var form) && _pokemon.Form != form)
        {
            _pokemon.ChangeForm(form, batchId);
        }
    }

    /// <inheritdoc />
    public override void OnRemove()
    {
        if (_pokemon is null)
            return;
        if (_pokemon.BattleData?.BattleSide.VolatileScripts.TryGet<Side.FlowerGiftEffect>(out var script) == true)
        {
            script.OnRemoved(_pokemon);
        }

        if (_pokemon.Species.Name != "cherrim")
            return;

        EventBatchId batchId = new();
        var defaultForm = _pokemon.Species.GetDefaultForm();
        if (_pokemon.Form != defaultForm)
        {
            _pokemon.ChangeForm(defaultForm, batchId);
        }
    }
}