package thb.jeanluc.adventure.command.impl;

import thb.jeanluc.adventure.command.Command;
import thb.jeanluc.adventure.game.Combinations;
import thb.jeanluc.adventure.game.GameContext;
import thb.jeanluc.adventure.model.item.Item;

import java.util.List;
import java.util.Optional;

/**
 * With one argument, invokes the item-specific {@link Item#use(GameContext)}
 * action; the item must be in the player's inventory or the current room.
 * With two arguments ({@code use <item> on <item>}), delegates to the
 * combination engine. Usage: {@code use <item>} or {@code use <item> on <item>}.
 */
public class UseCommand implements Command {

    @Override
    public void execute(GameContext ctx, List<String> args) {
        if (args.isEmpty()) {
            ctx.getIo().write("Use what?");
            return;
        }
        if (args.size() >= 2) {
            Combinations.tryUse(ctx, args.get(0), args.get(1));
            return;
        }
        String itemId = args.getFirst();
        Optional<Item> item = ctx.getPlayer().findItem(itemId);
        if (item.isEmpty()) {
            item = ctx.getPlayer().getCurrentRoom().findItem(itemId);
        }
        if (item.isEmpty()) {
            ctx.getIo().write("There is no '" + itemId + "' here or in your inventory.");
            return;
        }
        item.get().use(ctx);
    }

    @Override
    public String help() {
        return "use <item>  -  use an item; or  use <item> on <item>  to combine them";
    }
}
