/*
 * 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;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

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

	private List<LookaheadReader> readers;

	public DcReader(LookaheadReader rd) {
		readers = new ArrayList<LookaheadReader>();
		readers.add(rd);
	}

	public LookaheadReader peek() {
		return readers.get(readers.size() - 1);
	}

	public void pushOrSetStringAsReader(String s) throws IOException {
		LookaheadReader rd;

		rd = new LookaheadReader(new StringReader(s), 1);
		if(peek().isEof()) {
			readers.set(readers.size() - 1, rd);
		} else {
			readers.add(rd);
		}
	}

	public void pushStringAsReader(String s) throws IOException {
		LookaheadReader rd;

		rd = new LookaheadReader(new StringReader(s), 1);
		readers.add(rd);
	}

	public int getLevel() {
		return readers.size() - 1;
	}

	public void pop() {
		readers.remove(readers.size() - 1);
	}

	public void close() throws IOException {
		if(readers != null) {
			for(Reader r : readers)  r.close();
			readers = null;
		}
	}

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

		while(a < len) {
			if(readers.size() == 0) {
				return a > 0 ? a : -1;
			} else if((l = peek().read(cbuf, off + a, len - a)) < 0) {
				peek().close();
				readers.remove(readers.size() - 1);
			} else {
				a += l;
			}
		}
		return len;
	}

}
