using PkmnLib.Plugin.Gen7.Scripts.Side;
using PkmnLib.Plugin.Gen7.Scripts.Weather;

namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

/// <summary>
/// This move reduces damage from physical and special moves for five turns. This can be used only in a hailstorm. 
/// </summary>
/// <remarks>
/// Aurora Veil reduces the damage done to the user by physical and special moves for five turns by half; in battles
/// beside Single Battles, Aurora Veil protects the user and all allies, but only reduces damage by (roughly) a third
/// rather than half (specifically, with a multiplier of 2732/4096). It does not reduce damage done by self-inflicted
/// confusion damage, critical hits, or moves that deal direct damage. Aurora Veil can only be used during hail or snow,
/// but the effect remains even after hail or snow ends; Cloud Nine and Air Lock will cause Aurora Veil to fail even if
/// it is hailing or snowing.
/// <br/>
/// While it can be active at the same time as Reflect and Light Screen, the damage reduction effects do not stack.
/// Aurora Veil is removed from a Pokémon's side of the field if it is hit by Brick Break, Defog, Psychic Fangs, or
/// Raging Bull, or if a Pokémon with Screen Cleaner is sent out. Pokémon with the Ability Infiltrator ignore the effects
/// of Aurora Veil when attacking.
/// <br/>
/// If a Light Clay is held when Aurora Veil is used, it will extend the duration of Aurora Veil from 5 to 8 turns. 
/// </remarks>
[Script(ScriptCategory.Move, "aurora_veil")]
public class AuroraVeil : Script, IScriptOnSecondaryEffect
{
    /// <inheritdoc />
    public void OnSecondaryEffect(IExecutingMove move, IPokemon target, byte hit)
    {
        var battle = move.User.BattleData?.Battle;
        if (battle == null)
            return;

        if (battle.WeatherName != ScriptUtils.ResolveName<Hail>())
        {
            move.GetHitData(target, hit).Fail();
            return;
        }

        var side = battle.Sides[move.User.BattleData!.SideIndex];

        var args = new CustomTriggers.AuroraVeilDurationArgs(move, 5);
        move.User.RunScriptHook<IScriptCustomTrigger>(x => x.CustomTrigger(CustomTriggers.AuroraVeilDuration, args));
        var numberOfTurns = args.Duration;

        var script = side.VolatileScripts.StackOrAdd(ScriptUtils.ResolveName<AuroraVeilEffect>(), () =>
        {
            var effect = new AuroraVeilEffect(numberOfTurns);
            return effect;
        });
        ((AuroraVeilEffect)script!.Script!).NumberOfTurns = numberOfTurns;
    }
}