package lc.mecha.cli;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class CommandRouter<E> {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(CommandRouter.class);
    private HashMap<String, E> commands = new HashMap<>();

    @Override
    public String toString() {
        return "CommandRouter{" +
                "commands=" + commands +
                '}';
    }

    public CommandRoute<E> route(String name) {
        // Try the easiest thing first.

        logger.info("Route called. List: {}", commands);
        E cmd = commands.get(name);
        if (cmd != null) {
            logger.info("Located direct command! {}", cmd);
            return new CommandRoute<>(name, cmd);
        }

        // Not so lucky
        HashMap<String, E> matches = new HashMap<>();
        for (Map.Entry<String, E> entry : commands.entrySet()) {
            if (entry.getKey().startsWith(name)) matches.put(entry.getKey(), entry.getValue());
        }
        if (matches.size() > 0) return new CommandRoute<>(matches);

        logger.info("Failed to locate a matching command: {} {}", name, commands);
        return null;
    }

    public void putCommand(String name, E cmd) {
        commands.put(name, cmd);
    }

    public Collection<String> keySet() {
        return commands.keySet();
    }
}
