package com.touwolf.devenv.cli;

import com.beust.jcommander.JCommander;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import org.bridje.ioc.Ioc;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

// see: http://jcommander.org/
public class Main
{
    public static void main(String... raw) throws IOException
    {
        Args args = new Args();
        JCommander commander = new JCommander(args);
        commander.parse(raw);
        String cmd = args.command();
        if (cmd == null)
        {
            cmd = "usage";
        }

        Writer writer = new PrintWriter(System.out);
        Command command = findCommand(cmd);
        if (command != null)
        {
            command.execute(args, writer);
        }
        else
        {
            writer.write(String.format("Command %s not exists!", cmd));
        }
        writer.flush();
    }

    @Nullable
    private static Command findCommand(@NotNull String name)
    {
        Command[] commands = Ioc.context().findAll(Command.class);
        for (Command command : commands)
        {
            if (command.alias().contains(name))
            {
                return command;
            }
        }
        return null;
    }
}