package de.hsadmin.jscli;

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) {
		ConsoleWrapper console = null;
		try {
			CommandlineParser cmdParser = new CommandlineParser(args);
			String runAs = cmdParser.getRunAs();
			console = new ConsoleWrapper();
			console.open(runAs + "@hsadmin> ");
			JSONFormatter formatter = new JSONFormatter();
			ScriptClient scriptClient = new ScriptClient(console, cmdParser.getUser(), runAs);
			String file = cmdParser.getFile();
			if (file != null && file.length() > 0) {
				if ("-".equals(file)) {
					scriptClient.execute(new InputStreamReader(System.in));
					console.println(formatter.format(scriptClient.getLastRpcResult()));
				} else {
					File fileHandle = new File(file);
					try {
						scriptClient.execute(new FileReader(fileHandle));
						console.println(formatter.format(scriptClient.getLastRpcResult()));
					} catch (FileNotFoundException e) {
						System.err.println("File not found: " + file);
					}
				}
			}
			String expr = cmdParser.getExpression();
			if (expr != null && expr.length() > 0) {
				scriptClient.execute(expr);
				console.println(formatter.format(scriptClient.getLastRpcResult()));
			}
			if (cmdParser.isInteractive()) {
				String command = console.readInput();
				while (!("bye".equals(command.trim()) || "exit".equals(command.trim()) || "quit".equals(command.trim()))) {
					try {
						scriptClient.execute(command);
						console.println(formatter.format(scriptClient.getLastRpcResult()));
					} catch (Exception e) {
						console.println("Error: " + e.getLocalizedMessage() + "\n");
					}
					command = console.readInput();
				}
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
			System.exit(-1);
		}
	}

}
