package main;

import java.awt.Color;
import java.util.ArrayList;

import logging.ConsoleOutput;
import logging.Log;
import logging.LogLevel;
import tools.commandlineparser.ArgumentParser;
import tools.commandlineparser.Command;
import workerthreads.TestDatabaseWorker;
import workerthreads.changedates.ChangeDatesWorker;
import data.DatabaseSettings;
import data.Settings;

/**
 * This class provides application flow logic when started with switch
 * -commandline.
 * 
 * start() method is invoked from Main.java.main
 * 
 * @author Martin Pabst, 2010
 * 
 */

public class CommandlineStarter {

	private String[] args;

	public CommandlineStarter(String[] args) {
		this.args = args;
	}

	/**
	 * Main method. Reads settings and anonymizes/restores database
	 */
	public void start() {

		/**
		 * program has been started on command line, so do output on command
		 * line.
		 */
		Log.setLogOutput(new ConsoleOutput());

		DatabaseSettings.readSettings();
		Settings.readSettings();

		/**
		 * is database running?
		 */
		TestDatabaseWorker testDatabaseWorker = new TestDatabaseWorker(null);
		testDatabaseWorker.testDatabase();

		if (DatabaseSettings.isDatabaseConnectionOK()) {

			ArgumentParser ap = new ArgumentParser(args);

			ArrayList<Command> changeDateCommands = ap
					.getCommands("-changedates");

			if (changeDateCommands.size() > 0) {

				Log.outlColor("Aendere Datumsangaben:", LogLevel.useful,
						Color.blue);

				int globalDelta = 0;

				Command command = changeDateCommands.get(0);

				if (command.getParameters().size() > 0) {
					globalDelta = Integer.parseInt(command.getParameters().get(
							0));
				}

				ChangeDatesWorker worker = new ChangeDatesWorker(null,
						globalDelta);
				worker.doInForeground();

			}

		} else {
			Log.outl("", LogLevel.error);
			Log.outlColor(
					"Kann leider keine Datenbankverbindung herstellen, daher Programmabbruch. ",
					LogLevel.error, Color.red);
		}

	}

}
