/*
 * 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.dc;

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

/**
 * 
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/07/14
 */
public class LookaheadReader extends Reader {

	private Reader rd;
	private char[] buf;
	private int blen;

	public LookaheadReader(Reader rd, int n) throws IOException {
		if(n <= 0)  throw new IllegalArgumentException();
		this.rd   = rd;
		this.buf  = new char[n];
		this.blen = rd.read(this.buf);
	}

	public void close() throws IOException {
		rd.close();
	}

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

		if(blen <= 0) {
			return -1;
		} else if(len < blen) {
			l = blen - len;
			System.arraycopy(buf, 0, cbuf, off, len);
			System.arraycopy(buf, len, buf, 0, l);
			blen = len + rd.read(buf, cbuf.length, l);
			return len;
		} else if(len == blen) {
			System.arraycopy(buf, 0, cbuf, off, len);
			blen = rd.read(buf, 0, len);
			return len;
		} else {
			System.arraycopy(buf, 0, cbuf, off, blen);
			m = blen;
			if((l = rd.read(buf, off + len, len - blen)) < 0) {
				blen = 0;
				buf  = null;
				return m;
			} else {
				blen = rd.read(buf);
				return m + l;
			}
		}
	}

	public boolean isEof() {
		return blen <= 0;
	}

	public char lookahead(int n) {
		if(n < 0 || n >= blen) {
			throw new IllegalArgumentException();
		}
		return buf[n];
	}

}
