using PkmnLib.Plugin.Gen7.Scripts.Pokemon;

namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "gravity")]
public class Gravity : Script, IScriptOnSecondaryEffect
{
    /// <inheritdoc />
    public void OnSecondaryEffect(IExecutingMove move, IPokemon target, byte hit)
    {
        var battleData = target.BattleData;
        if (battleData == null)
            return;

        battleData.Battle.Volatile.StackOrAdd("gravity", () =>
        {
            battleData.Battle.Library.ScriptResolver.TryResolve(ScriptCategory.Battle, "gravity",
                new Dictionary<StringKey, object?>(), out var script);
            return script;
        });

        var chargeBounceEffect = ScriptUtils.ResolveName<ChargeBounceEffect>();
        var flyEffect = ScriptUtils.ResolveName<ChargeFlyEffect>();
        var skyDropEffect = ScriptUtils.ResolveName<ChargeSkyDropEffect>();
        var telekinesisEffect = ScriptUtils.ResolveName<TelekinesisEffect>();

        foreach (var pokemon in battleData.Battle.Sides.SelectMany(x => x.Pokemon).WhereNotNull())
        {
            if (pokemon.Volatile.Contains(chargeBounceEffect))
                pokemon.Volatile.Remove(chargeBounceEffect);
            if (pokemon.Volatile.Contains(flyEffect))
                pokemon.Volatile.Remove(flyEffect);
            if (pokemon.Volatile.Contains(skyDropEffect))
                pokemon.Volatile.Remove(skyDropEffect);
            if (pokemon.Volatile.Contains(telekinesisEffect))
                pokemon.Volatile.Remove(telekinesisEffect);
        }
    }
}