package fi.helsinki.cs.tmc.cli.command.core;

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.command.LoginCommand;
import fi.helsinki.cs.tmc.cli.io.Io;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractCommand {
    private static final Logger logger = LoggerFactory.getLogger(LoginCommand.class);

    private Application app;

    protected void setApplication(Application app) {
        this.app = app;
    }

    protected Application getApp() {
        return this.app;
    }

    /**
     * Method runs the command.
     *
     * @param args Command line arguments for this command.
     * @param io The terminal IO object
     */
    public abstract void run(CommandLine args, Io io);

    public abstract void getOptions(Options options);

    private Options getOptions() {
        Options options;

        options = new Options();
        options.addOption("h", "help", false, "Get this help message.");
        getOptions(options);

        return options;
    }

    public void execute(String[] stringArgs, Io io) {
        GnuParser parser = new GnuParser();
        CommandLine args;
        Options options = getOptions();

        try {
            args = parser.parse(options, stringArgs);
        } catch (ParseException e) {
            logger.warn("Invalid command line arguments.", e);
            io.println("Invalid command line arguments.");
            io.println(e.getMessage());
            return;
        }

        if (args.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            Class<Command> klass = (Class<Command>)(Class)this.getClass();
            Command command = CommandFactory.getCommand(klass);
            formatter.printHelp("tmc " + command.name(), options);
            return;
        }

        run(args, io);
    }
}

@@ -445,16 +445,45 @@
 ctory;%0A%0A
+import java.io.PrintWriter;%0A%0A
 public a
@@ -1970,24 +1970,25 @@
 and(klass);%0A
+%0A
             
@@ -1991,60 +1991,292 @@
     
-formatter.printHelp(%22tmc %22 + command.name(), options
+String usage = %22tmc %22 + command.name();%0A            String header = %22%5Cn%22 + command.desc() + %22%5CnOptions:%22;%0A            String footer = %22%5CnCopyright(C) 2016 TestMyCode%5CnSome rights reserved.%22;%0A            formatter.printHelp(new PrintWriter(io), 80, usage, header, options, 2, 0, footer
 );%0A 

Print the help message to TerminalIO.