/*
 * 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 java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

import net.morilib.awk.nano.AwkCastException;
import net.morilib.awk.nano.expr.AwkExpression;
import net.morilib.awk.nano.misc.System2;
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;

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

	private static final AwkValue TWO = AwkInteger.valueOf(2);

	/**
	 * 上書きを表します。
	 */
	public static final int OVERWRITE = 0;

	/**
	 * 追加を表します。
	 */
	public static final int APPEND = 1;

	/**
	 * パイプへの出力を表します。
	 */
	public static final int PIPE = 2;

	AwkExpression[] exprs;
	AwkExpression filename;
	int flag;

	/**
	 * 中間表現を取得します。
	 * 
	 * @param filename ファイル名
	 * @param exprs 出力する式の集合
	 * @param flag  フラグ
	 */
	public AwkPrint(AwkExpression filename,
			List<AwkExpression> exprs, int flag) {
		this.filename = filename;
		this.exprs    = exprs.toArray(new AwkExpression[0]);
		this.flag     = flag;
	}

	/* (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) {
		String ofs = ns.getOFS(), ors = ns.getORS();
		StringWriter x = null;
		LineWriter w = null;
		AwkValue g;

		try {
			if(filename == null) {
				w = f.getStdout();
			} else if((g = filename.eval(ns, f)).equals(TWO)) {
				w = f.getStderr();
			} else if(g.equals(AwkInteger.ONE)) {
				w = f.getStdout();
			} else if(!g.isString()) {
				throw new AwkCastException("string, 1 or 2 required");
			} else if(flag == APPEND) {
				w = f.getWriter(filename.eval(ns, f).toString(ns));
			} else if(flag == PIPE) {
				x = new StringWriter();
				w = new PrintLineWriter(new PrintWriter(x));
			} else {
				w = f.openWriter(filename.eval(ns, f).toString(ns));
			}

			if(exprs.length == 0) {
				w.print(ns.referField(0).toString(ns));
				w.print(ors);
			} else {
				for(int i = 0; i < exprs.length; i++) {
					w.print(exprs[i].eval(ns, f).toString(ns));
					w.print((i + 1 < exprs.length) ? ofs : ors);
				}
			}
			w.flush();

			// piped
			if(x != null) {
				System2.system(
						filename.eval(ns, f).toString(ns),
						x.toString(),
						System.out);
			}
			return AwkValue.TRUE;
		} catch (IOException e1) {
			ns.getRoot().assign("ERRNO",
					AwkString.valueOf(e1.getMessage()));
			return AwkValue.FALSE;
		} finally {
			if(w != null)  w.flush();
		}
	}

}
