package mage.cards.l;

import java.util.UUID;

import mage.MageObject;
import mage.MageObjectReference;
import mage.abilities.Ability;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.common.TargetCreaturePermanent;
import mage.watchers.common.ControlledModifiedCreatureAsSpellCastWatcher;

/**
 *
 * @author weirddan455
 */
public final class LethalExploit extends CardImpl {

    public LethalExploit(UUID ownerId, CardSetInfo setInfo) {
        super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{B}");

        // Target creature gets -2/-2 until end of turn. It gets an additional -1/-1 until end of turn for each modified creature you controlled as you cast this spell.
        this.getSpellAbility().addEffect(new LethalExploitEffect());
        this.getSpellAbility().addTarget(new TargetCreaturePermanent());
        this.getSpellAbility().addWatcher(new ControlledModifiedCreatureAsSpellCastWatcher());
    }

    private LethalExploit(final LethalExploit card) {
        super(card);
    }

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

class LethalExploitEffect extends ContinuousEffectImpl {

    private int boostValue = -2;

    public LethalExploitEffect() {
        super(Duration.EndOfTurn, Layer.PTChangingEffects_7, SubLayer.ModifyPT_7c, Outcome.UnboostCreature);
        this.staticText = "Target creature gets -2/-2 until end of turn. It gets an additional -1/-1 until end of turn for each modified creature you controlled as you cast this spell";
    }

    private LethalExploitEffect(final LethalExploitEffect effect) {
        super(effect);
        this.boostValue = effect.boostValue;
    }

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

    @Override
    public void init(Ability source, Game game) {
        super.init(source, game);
        ControlledModifiedCreatureAsSpellCastWatcher watcher = game.getState().getWatcher(ControlledModifiedCreatureAsSpellCastWatcher.class);
        MageObject sourceObject = source.getSourceObject(game);
        if (watcher != null && sourceObject != null) {
            boostValue -= watcher.getModifiedCreatureCount(new MageObjectReference(sourceObject, game));
        }
    }

    @Override
    public boolean apply(Game game, Ability source) {
        Permanent target = game.getPermanent(source.getFirstTarget());
        if (target == null) {
            return false;
        }
        target.addPower(boostValue);
        target.addToughness(boostValue);
        return true;
    }
}
