package thb.jeanluc.adventure.command.impl;

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

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

/**
 * Shorthand for using a {@link ReadableItem}. Behaves like
 * {@link UseCommand} but writes a more helpful message when applied to a
 * non-readable item. Usage: {@code read <item-id>}.
 */
public class ReadCommand implements Command {

    @Override
    public void execute(GameContext ctx, List<String> args) {
        if (args.isEmpty()) {
            ctx.getIo().write("Read what?");
            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;
        }
        if (item.get() instanceof ReadableItem readable) {
            readable.use(ctx);
        } else {
            ctx.getIo().write("There is nothing to read on the " + item.get().getName() + ".");
        }
    }

    @Override
    public String help() {
        return "read <item>  -  read the text of a readable item";
    }
}
