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

import java.io.IOException;
import java.io.InputStream;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/05/24
 */
public class ConsoleInputStream extends InputStream {

	private byte[] line = null;
	private int point;

	//
	ConsoleInputStream() { }

	/**
	 * 
	 * @return
	 */
	public static InputStream console() {
		if(System.console() == null) {
			return System.in;
		} else {
			return new ConsoleInputStream();
		}
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#read()
	 */
	@Override
	public int read() {
		int c;

		if(line == null) {
			point = 0;
			line  = System.console().readLine().getBytes();
			return read();
		} else if(point < line.length) {
			c = line[point++];
			return (c < 0) ? 256 + c : c;
		} else {
			line = null;
			return '\n';
		}
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#read(byte[], int, int)
	 */
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		int c;

		for(int i = 0; i < len; i++) {
			if((c = read()) < 0) {
				return i > 0 ? i : -1;
			} else {
				b[i] = (byte)c;
				if(c == '\n')  return i + 1;
			}
		}
		return len;
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#close()
	 */
	@Override
	public void close() {
	}

}
