package leigh.mud.engine.cmd;

import leigh.continuity.cmd.CommandHandler;
import leigh.mecha.cli.CommandRoute;
import leigh.mecha.cli.CommandRouter;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.Arrays;
import java.util.Map;

/**
 * CommandFrame is a base command implementation that in turn offers subcommands. CommandFrames may be nested
 * to provide complex command structures.
 *
 * @author Alex Leigh
 */
public class CommandFrame implements CommandHandler {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(CommandFrame.class);
    private final CommandRouter<CommandHandler> subcommands = new CommandRouter<>();

    @Override
    /**
     * Attempt to route a subcommand from this command invocation.
     */
    public String handle(String[] cmd) throws Exception {
        // cmd[0] == this
        // cmd[1] == wanted
        // cmd[2...] == args

        // TODO: Check for null

        logger.info("Called: {} {}", cmd.length, Arrays.toString(cmd));

        if (cmd.length < 2) {
            return "Incomplete command.";
        }

        CommandRoute<CommandHandler> handler = subcommands.route(cmd[1]);

        // TODO Get the unknown response from the session

        if (handler == null) return "Unknown command.";

        Map<String, CommandHandler> cmds = handler.getCommands();
        if (cmds.size() == 0) return "Unknown command.";
        // Which ones?
        if (cmds.size() > 1) return "Ambiguous commands.";

        CommandHandler h = (CommandHandler) cmds.values().toArray()[0];
        String[] subCmd = Arrays.copyOfRange(cmd, 1, cmd.length);
        logger.info("Built subcmd: {}", Arrays.toString(subCmd));

        return h.handle(subCmd);
    }

    public void putCommand(String name, CommandHandler handler) {
        subcommands.putCommand(name, handler);
    }
}
