/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.awk.misc;

import java.io.IOException;
import java.io.Reader;

public class PromptReader implements PushbackLineNumberReadable {

	//
	private int unread = -1;
	private int lineno = 1;
	private Reader rd;
	private String prompt1, prompt2, prompt;
	private boolean isno = false;

	/**
	 * 
	 * @param rd
	 */
	public PromptReader(String prompt1, String prompt2, Reader rd) {
		this.prompt1 = prompt1;
		this.prompt2 = this.prompt = prompt2;
		this.rd = rd;
		System.out.print(prompt1);
	}

	/**
	 * 
	 * @param c
	 * @throws IOException
	 */
	public void unread(int c) throws IOException {
		unread = c;
	}

	/**
	 * 
	 * @return
	 */
	public int getLineNumber() {
		return lineno;
	}

	public void close() throws IOException {
		// do nothing
	}

	public int read(char[] cbuf, int off, int len) throws IOException {
		int c;

		for(int i = off; i < off + len; i++) {
			if((c = read()) < 0) {
				return i - off;
			} else {
				cbuf[i] = (char)c;
			}
		}
		return len;
	}

	public int read(char[] cbuf) throws IOException {
		return read(cbuf, 0, cbuf.length);
	}

	public int read() throws IOException {
		int c;

		if(isno)  System.out.print(prompt);
		isno = false;
		if(unread >= 0) {
			c = unread;
			unread = -1;
			return c;
		} else if((c = rd.read()) < 0) {
			return -1;
		} else if(c == '\r') {
			return read();
		} else if(c == '\n') {
			prompt = prompt2;
			isno = true;
			return c;
		} else {
			return c;
		}
	}

	public void resetPrompt() throws IOException {
		prompt = prompt1;
		while(rd.ready())  rd.read();
		unread = -1;
		isno = true;
	}

	public boolean isNewline() throws IOException {
		int c;

		if(unread == '\n') {
			return true;
		} else if(unread < 0) {
			while((c = rd.read()) == ' ' || c == '\t' || c == '\r');
			unread = c;
			return isno = (c == '\n');
		} else {
			return false;
		}
	}

}
