/*
 * 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.awk.nano.io;

import java.io.IOException;

import net.morilib.awk.nano.AwkCastException;
import net.morilib.awk.nano.expr.AwkExpression;
import net.morilib.awk.nano.namespace.AwkNamespace;
import net.morilib.awk.nano.value.AwkInteger;
import net.morilib.awk.nano.value.AwkString;
import net.morilib.awk.nano.value.AwkValue;

/**
 * getline文の中間表現です。
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/03/23
 */
public class AwkGetline extends AwkExpression {

	private static final AwkValue ZERO = AwkInteger.ZERO;

	private AwkExpression filename, pipe;
	private String varname;

	/**
	 * 中間表現を得ます。
	 * 
	 * @param varname  変数名
	 * @param filename ファイル名
	 * @param pipe     パイプコマンド
	 */
	public AwkGetline(String varname, AwkExpression filename,
			AwkExpression pipe) {
		this.varname  = varname;
		this.filename = filename;
		this.pipe     = pipe;
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.expr.AwkExpression#eval(net.morilib.awk.namespace.AwkNamespace, net.morilib.awk.io.AwkFiles)
	 */
	@Override
	public AwkValue eval(AwkNamespace ns, AwkFiles f) {
		RecordReader r = null;
		AwkValue v;
		String s;

		try {
			if(pipe != null) {
				r = f.getReadPipe(pipe.eval(ns, f).toString(ns));
			} else if(filename == null) {
				r = f.getReader(null);
			} else if((v = filename.eval(ns, f)).equals(ZERO)) {
				r = f.getReader(null);
			} else if(!v.isString()) {
				throw new AwkCastException("string or 0 required");
			} else {
				r = f.getReader(v.toString(ns));
			}

			s = r.readRecord(ns.getRS());
			if(s == null) {
				return AwkValue.FALSE;
			} else if(varname != null) {
				ns.assign(varname, AwkString.valueOf(s));
				return AwkValue.TRUE;
			} else {
				ns.setField(s);
				return AwkValue.TRUE;
			}
		} catch (IOException e) {
			ns.getRoot().assign("ERRNO",
					AwkString.valueOf(e.getMessage()));
			return AwkValue.IOERROR;
		}
	}

}
