package ca.carleton.gcrc.jsCompressor.app;

import java.util.Iterator;
import java.util.List;

import ca.carleton.gcrc.jsCompressor.app.options.CompressOptions;
import ca.carleton.gcrc.jsCompressor.app.options.CompressOptionsFactory;
import ca.carleton.gcrc.jsCompressor.app.task.CompressTask;
import ca.carleton.gcrc.jsCompressor.app.task.CompressTaskFactory;

public class JsCompress  {
	static public void main(String[] args) {
		JsCompress obj = new JsCompress();
		obj.execute(args);
	}

	private void execute(String[] args) {
		CompressOptions compressOptions = null;
		try {
			compressOptions = CompressOptionsFactory.fromCommandLineArguments(args);
		} catch(Exception e) {
			reportError("Error detected while parsing command line options",e);
		}
		
		// Get task list from options
		List<CompressTask> tasks = null;
		try {
			tasks = CompressTaskFactory.tasksFromOptions(compressOptions);
		} catch (Exception e) {
			reportError("Error detected while establishing task list",e);
		}
		
		// Execute tasks
		try {
			Iterator<CompressTask> itTask = tasks.iterator();
			while( itTask.hasNext() ) {
				CompressTask task = itTask.next();
				
				task.execute();
			}
		} catch (Exception e) {
			reportError("Error detected during compression",e);
		}
	}
	

//	private void reportError(String message) {
//		reportError(message,null);
//	}
	
	private void reportError(String message, Throwable error) {
		System.err.println(message);
		
		if( null != error ) {
			System.err.println("Error: "+error.getMessage());
			Throwable cause = error.getCause();
			while( null != cause ) {
				System.err.println("Caused by: "+cause.getMessage());
				
				cause = cause.getCause();
			}
		}
		
		System.err.println("Usage: "+getClass().getSimpleName()+" --input-file <input-file-name> [--output-file <output-file-name>]");
	}
}
