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

import java.io.IOException;
import java.io.PushbackReader;

import net.morilib.sed.SedCommand;
import net.morilib.sed.SedCommandBundle;
import net.morilib.sed.SedCommandParser;
import net.morilib.sed.SedLineOption;

/**
 * 行編集コマンドをパースするパーサの基底クラスです。
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/03
 */
public abstract class SedLineCommandParser
implements SedCommandParser {

	/**
	 * コマンドを得ます。
	 * 
	 * @param string 行
	 * @return 生成されたコマンド
	 */
	protected abstract SedCommand getCommand(String string);

	/**
	 * 行を検証します。
	 * 
	 * @param l 行コマンド
	 * @return 正しいときtrue
	 */
	protected boolean validate(SedLineOption l) {
		return true;
	}

	public SedCommand parse(SedCommandBundle bl,
			PushbackReader rd, SedLineOption l) throws IOException {
		StringBuffer b = new StringBuffer();
		boolean esc = false;
		int c;

		while(((c = rd.read()) >= 0 && c != '\n') || esc) {
			if(!esc) {
				if(!(esc = c == '\\'))  b.appendCodePoint(c);
			} else if(c == '\n') {
				esc = false;
				b.append('\n');
			} else {
				esc = false;
				b.append('\\').appendCodePoint(c);
			}
		}

		if(c >= 0)  rd.unread(c);
		if(b.length() > 0 && b.charAt(0) == '\n')  b.deleteCharAt(0);
		return getCommand(b.toString());
	}

}
