package thb.jeanluc.adventure.game;

import lombok.extern.slf4j.Slf4j;
import thb.jeanluc.adventure.model.Effect;
import thb.jeanluc.adventure.model.item.Item;

import java.util.List;

/** Applies {@link Effect}s to a {@link GameContext}. */
@Slf4j
public final class Effects {

    private Effects() {
    }

    public static void apply(Effect e, GameContext ctx) {
        switch (e.type()) {
            case SET_FLAG -> ctx.getState().set(e.arg());
            case CLEAR_FLAG -> ctx.getState().clear(e.arg());
            case GIVE_ITEM -> {
                Item it = ctx.getWorld().getItems().get(e.arg());
                if (it == null) {
                    log.warn("Effect GIVE_ITEM references unknown item '{}'", e.arg());
                } else {
                    ctx.getPlayer().addItem(it);
                }
            }
            case REMOVE_ITEM -> ctx.getPlayer().removeItem(e.arg());
            case SAY -> ctx.getIo().write(e.arg());
            case START_QUEST -> ctx.getQuestLog().start(e.arg());
        }
    }

    /** Applies each effect in order. A null list is a no-op. */
    public static void applyAll(List<Effect> effects, GameContext ctx) {
        if (effects == null) {
            return;
        }
        for (Effect e : effects) {
            apply(e, ctx);
        }
    }
}
