package mage.abilities.common;

import mage.MageObject;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.Effect;
import mage.constants.SetTargetPointer;
import mage.constants.Zone;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.permanent.Permanent;
import mage.target.targetpointer.FixedTarget;

/**
 * @author LevelX2
 */
public class ExploitCreatureTriggeredAbility extends TriggeredAbilityImpl {

    private final SetTargetPointer setTargetPointer;

    public ExploitCreatureTriggeredAbility(Effect effect) {
        this(effect, false);
    }

    public ExploitCreatureTriggeredAbility(Effect effect, boolean optional) {
        this(effect, optional, SetTargetPointer.NONE);
    }

    public ExploitCreatureTriggeredAbility(Effect effect, boolean optional, SetTargetPointer setTargetPointer) {
        super(Zone.BATTLEFIELD, effect, optional);
        this.setTargetPointer = setTargetPointer;
        // For example: if the creature with the Exploit ability is sacrificed, the trigger ability must use the controller of the LKI, not the owner
        setLeavesTheBattlefieldTrigger(true); // https://github.com/magefree/mage/issues/8317
        setTriggerPhrase("When {this} exploits a creature, ");
    }

    protected ExploitCreatureTriggeredAbility(final ExploitCreatureTriggeredAbility ability) {
        super(ability);
        this.setTargetPointer = ability.setTargetPointer;
    }

    @Override
    public ExploitCreatureTriggeredAbility copy() {
        return new ExploitCreatureTriggeredAbility(this);
    }

    @Override
    public boolean checkEventType(GameEvent event, Game game) {
        return event.getType() == GameEvent.EventType.EXPLOITED_CREATURE;
    }

    @Override
    public boolean checkTrigger(GameEvent event, Game game) {
        if (event.getSourceId().equals(getSourceId())) {
            for (Effect effect : getEffects()) {
                if (setTargetPointer == SetTargetPointer.PERMANENT) {
                    effect.setTargetPointer(new FixedTarget(event.getTargetId(), game));
                }
            }
            return true;
        }
        return false;
    }
}
