package de.hsadmin.jscli;

import java.io.IOException;

import jline.ConsoleReader;
import jline.SimpleCompletor;

public class ConsoleWrapper {

	private ConsoleReader cons;
	private String prompt;

	public void open(final String prompt) throws JSCliException {
		this.prompt = prompt;
		try {
			cons = new ConsoleReader();
			cons.setDefaultPrompt(prompt);
		} catch (IOException e) {
			throw new JSCliException(e);
		}
	}

	public String readInput() throws JSCliException {
		try {
			String line = cons.readLine();
			while (line.trim().endsWith("\\")) {
				line = line.substring(0, line.length() - 1) + "\n" + cons.readLine(">");
			}
			return line;
		} catch (IOException e) {
			throw new JSCliException(e);
		}
	}
	
	public void println(String text) throws JSCliException {
		try {
			if (cons != null) {
				cons.printString(text);
				cons.printNewline();
			} else {
				throw new JSCliException("cannot write console");
			}
		} catch (IOException e) {
			throw new JSCliException(e);
		}
	}

	public String readPassword() throws JSCliException {
		try {
			String pw = cons.readLine("Password: ", new Character('*'));
			cons.setDefaultPrompt(prompt);
			return pw;
		} catch (IOException e) {
			throw new JSCliException(e);
		}
	}

	public void codeCompletion(String[] candidateStrings) {
		cons.addCompletor(new SimpleCompletor(candidateStrings));
	}

}
