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

import java.io.IOException;

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

/**
 * 
 *
 *
 * @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;

	public AwkGetline(String varname, AwkExpression filename,
			AwkExpression pipe) {
		this.varname  = varname;
		this.filename = filename;
		this.pipe     = pipe;
	}

	@Override
	public AwkValue eval(AwkNamespace ns, AwkFiles f) {
		AwkReader 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) {
			return AwkValue.IOERROR;
		}
	}

}
