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

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

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2014/01/15
 */
public class DecultureReader extends FilterReader {

	//
	private static final int INIT = 1000;
	private static final int LEN  = 1001;
	private static final int PER1 = 1011;
	private static final int PER2 = 1012;
	private static final int OPR1 = 1021;
	private static final int OPR2 = 1022;

	//
	private int state = INIT;
	private int unget;

	/**
	 * @param in
	 */
	public DecultureReader(Reader in) {
		super(in);
	}

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

		while(true) {
			switch(state) {
			case INIT:
				if((c = in.read()) < 0) {
					return -1;
				} else if(c == '%') {
					state = PER1;
				} else if(c == '\n') {
					return c;
				} else {
					state = LEN;
					return c;
				}
				break;
			case LEN:
				if((c = in.read()) < 0) {
					return -1;
				} else if(c == '\n') {
					state = INIT;
					return c;
				} else {
					return c;
				}
			case PER1:
				if((c = in.read()) < 0) {
					return -1;
				} else if(c == '%') {
					state = PER2;
				} else {
					unget = c;
					state = OPR1;
					return '%';
				}
				break;
			case PER2:
				if((c = in.read()) < 0) {
					return -1;
				} else if(c == '\n') {
					return -1;
				} else if(c != '\r') {
					unget = c;
					state = OPR2;
					return '%';
				}
				break;
			case OPR1:
				state = unget == '\n' ? INIT : LEN;
				return unget;
			case OPR2:
				state = OPR1;
				return '%';
			}
		}
	}

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

		for(int k = off; k < off + len; k++) {
			if((c = read()) < 0) {
				return k > off ? k - off : -1;
			} else {
				cbuf[k] = (char)c;
			}
		}
		return len;
	}

}
