package de.hsadmin.jscli;

import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;


public class Main {

	public static void main(String[] args) {
		try {
			JSONFormatter formatter = new JSONFormatter();
			CommandlineParser cmdParser = new CommandlineParser(args);
			String runAs = cmdParser.getRunAs();
			ScriptClient scriptClient = new ScriptClient(cmdParser.getUser(), runAs);
			String file = cmdParser.getFile();
			if (file != null && file.length() > 0) {
				if ("-".equals(file)) {
					System.out.println(formatter.format(scriptClient.execute(new InputStreamReader(System.in))));
				} else {
					File fileHandle = new File(file);
					try {
						System.out.println(formatter.format(scriptClient.execute(new FileReader(fileHandle))));
					} catch (FileNotFoundException e) {
						System.err.println("file not found: " + file);
					}
				}
			}
			String expr = cmdParser.getExpression();
			if (expr != null && expr.length() > 0) {
				System.out.println(formatter.format(scriptClient.execute(expr)));
			}
			if (cmdParser.isInteractive()) {
				Console console = System.console();
				if (console == null) {
					throw new JSCliException("fatal error: console not found");
				}
				String command = console.readLine("%s@hsadmin>", runAs);
				if (command == null) {
					command = "";
				}
				while (!("bye".equals(command.trim()) || "exit".equals(command.trim()) || "quit".equals(command.trim()))) {
					try {
						console.printf("%s\n", formatter.format(scriptClient.execute(command)));
					} catch (Exception e) {
						console.printf("ERR: %s\n", e.getLocalizedMessage());
					}
					command = console.readLine("%s@hsadmin>", runAs);
					if (command == null) {
						command = "";
					}
					while (command.trim().endsWith("\\")) {
						command = command.substring(0, command.length() - 1) + 
								"\n" + console.readLine(">");
					}
				}
			}
		} catch (JSCliException e) {
			System.err.println(e.getMessage());
			System.exit(-1);
		}
	}
	
}
