/*
 * Copyright 2009-2010 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.lisp.nano.util;

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

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2014/02/17
 */
public class PeekableReader extends Reader {

	/**
	 * 
	 */
	public static final PeekableReader in;

	static {
		in = new PeekableReader(new InputStreamReader(System.in));
	}

	//
	private Reader rd;
	private int peek = -1;
	private int unget = -1;
	private boolean _notinit = true;

	/**
	 * 
	 * @param rd
	 */
	public PeekableReader(Reader rd) {
		this.rd = rd;
	}

	private void _read() throws IOException {
		peek = rd.read();
	}

	private void _init() throws IOException {
		if(_notinit) {
			_read();
			_notinit = false;
		}
	}

	/* (non-Javadoc)
	 * @see java.io.Reader#read()
	 */
	@Override
	public int read() throws IOException {
		int r;

		_init();
		if((r = unget) >= 0) {
			unget = -1;
		} else if((r = peek) >= 0) {
			r = peek;
			_notinit = true;
		}
		return r;
	}

	/* (non-Javadoc)
	 * @see java.io.Reader#read(char[], int, int)
	 */
	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		int o = off, l = len, r;

		_init();
		if(l-- > 0 && unget >= 0) {
			cbuf[o++] = (char)unget;
			unget = -1;
		} else {
			return 0;
		}

		if(l-- > 0 && peek >= 0) {
			cbuf[o++] = (char)peek;
			r = rd.read(cbuf, o, l) + (o - off);
			_read();
			return r;
		} else {
			return o - off;
		}
	}

	/**
	 * 
	 * @return
	 */
	public int peek() throws IOException {
		_init();
		return unget >= 0 ? unget : peek;
	}

	/**
	 * 
	 * @param c
	 */
	public void unget(int c) {
		unget = c;
	}

	/* (non-Javadoc)
	 * @see java.io.Reader#close()
	 */
	@Override
	public void close() throws IOException {
		rd.close();
	}

}
