namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;
///
/// Illusion is an ability that disguises the Pokémon as the last non-fainted Pokémon in the party until it takes damage.
///
/// Bulbapedia - Illusion
///
[Script(ScriptCategory.Ability, "illusion")]
public class Illusion : Script, IScriptOnIncomingHit
{
private IPokemon? _pokemon;
///
public override void OnAddedToParent(IScriptSource source)
{
if (source is not IPokemon pokemon)
throw new InvalidOperationException("Illusion can only be added to a Pokemon script source.");
_pokemon = pokemon;
}
///
public override void OnSwitchIn(IPokemon pokemon, byte position)
{
var battleData = pokemon.BattleData;
if (battleData is null)
return;
var lastNonFaintedPokemon = battleData.Battle.Parties.FirstOrDefault(p => p.Party.Any(pkmn => pkmn == pokemon))
?.Party.WhereNotNull().FirstOrDefault(x => x.IsUsable);
if (lastNonFaintedPokemon is null || lastNonFaintedPokemon == pokemon)
return;
pokemon.SetDisplaySpecies(lastNonFaintedPokemon.Species, lastNonFaintedPokemon.Form);
}
///
public override void OnRemove()
{
if (_pokemon is null)
return;
_pokemon.SetDisplaySpecies(null, null);
_pokemon.BattleData?.Battle.EventHook.Invoke(new AbilityTriggerEvent(_pokemon));
}
///
public void OnIncomingHit(IExecutingMove move, IPokemon target, byte hit)
{
if (_pokemon?.BattleData?.Battle is null)
return;
// Remove the illusion when the Pokémon takes damage
_pokemon.SetDisplaySpecies(null, null);
_pokemon.BattleData.Battle.EventHook.Invoke(new AbilityTriggerEvent(_pokemon));
}
}