using PkmnLib.Plugin.Gen7.Scripts.Utils;

namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "mirror_move")]
public class MirrorMove : Script, IScriptChangeMove
{
    /// <inheritdoc />
    public void ChangeMove(IMoveChoice choice, ref StringKey moveName)
    {
        var battleData = choice.User.BattleData;
        if (battleData == null)
            return;

        var battle = battleData.Battle;
        if (battle.ChoiceQueue == null)
            return;
        var currentTurn = battle.ChoiceQueue.LastRanChoice;
        var lastMove = battle.PreviousTurnChoices.SelectMany(x => x).OfType<IMoveChoice>()
            .TakeWhile(x => !Equals(x, currentTurn)).LastOrDefault(x => x.TargetPosition == choice.TargetPosition &&
                                                                        x.TargetSide == choice.TargetSide &&
                                                                        x.User.BattleData?.IsOnBattlefield == true);
        if (lastMove == null || !lastMove.ChosenMove.MoveData.CanCopyMove())
        {
            choice.Fail();
            return;
        }
        moveName = lastMove.ChosenMove.MoveData.Name;
    }
}