using PkmnLib.Plugin.Gen7.Scripts.Utils;

namespace PkmnLib.Plugin.Gen7.Scripts.Pokemon;

[Script(ScriptCategory.Pokemon, "encore")]
public class EncoreEffect : Script, IScriptForceTurnSelection, IScriptOnEndTurn
{
    private readonly IPokemon _owner;
    private readonly StringKey _move;
    private int _turns;

    public EncoreEffect(IPokemon owner, StringKey move, int turns)
    {
        _owner = owner;
        _move = move;
        _turns = turns;
    }

    /// <inheritdoc />
    public void ForceTurnSelection(IBattle battle, byte sideIndex, byte position, ref ITurnChoice? choice)
    {
        var opposingSideIndex = (byte)(_owner.BattleData?.SideIndex == 0 ? 1 : 0);
        choice = TurnChoiceHelper.CreateMoveChoice(_owner, _move, opposingSideIndex, position);
        if (choice is IMoveChoice { ChosenMove.CurrentPp: <= 0 } moveChoice)
        {
            choice = moveChoice.User.BattleData?.Battle.Library.MiscLibrary.ReplacementChoice(_owner, opposingSideIndex,
                position);
        }
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        _turns--;
        if (_turns <= 0)
        {
            RemoveSelf();
        }
    }
}