PreventionEffectData result = new PreventionEffectData(amountToPrevent);
if (!(event instanceof DamageEvent)) {
result.setError(true);
return result;
}
DamageEvent damageEvent = (DamageEvent) event;
GameEvent preventEvent = new GameEvent(GameEvent.EventType.PREVENT_DAMAGE, damageEvent.getTargetId(), damageEvent.getSourceId(), source.getControllerId(), damageEvent.getAmount(), false);
if (game.replaceEvent(preventEvent)) {
result.setReplaced(true);
return result;
}
if (event.getAmount() > amountToPrevent) {
result.setPreventedDamage(amountToPrevent);
damageEvent.setAmount(event.getAmount() - amountToPrevent);
} else {
result.setPreventedDamage(event.getAmount());
damageEvent.setAmount(0);
}
if (amountToPrevent != Integer.MAX_VALUE) {
// set remaining amount
result.setRemainingAmount(amountToPrevent -= result.getPreventedDamage());
}
MageObject damageSource = game.getObject(damageEvent.getSourceId());
MageObject preventionSource = game.getObject(source.getSourceId());
if (damageSource != null && preventionSource != null) {
MageObject targetObject = game.getObject(event.getTargetId());
String targetName = "";
if (targetObject == null) {
Player targetPlayer = game.getPlayer(event.getTargetId());
if (targetPlayer != null) {
targetName = targetPlayer.getName();
}
} else {
targetName = targetObject.getLogName();
}
StringBuilder message = new StringBuilder(preventionSource.getLogName()).append(": Prevented ");
message.append(Integer.toString(result.getPreventedDamage())).append(" damage from ").append(damageSource.getName());
if (!targetName.isEmpty()) {
message.append(" to ").append(targetName);
}
game.informPlayers(message.toString());
}
game.fireEvent(GameEvent.getEvent(GameEvent.EventType.PREVENTED_DAMAGE, damageEvent.getTargetId(), source.getSourceId(), source.getControllerId(), result.getPreventedDamage()));
return result;
}