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

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

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

	AwkExpression[] exprs;
	AwkExpression filename, format;
	int flag;

	/**
	 * 中間表現を取得します。
	 * 
	 * @param filename ファイル名
	 * @param format フォーマット
	 * @param exprs 出力する式の集合
	 * @param flag  フラグ
	 */
	public AwkPrintf(AwkExpression filename, AwkExpression format,
			List<AwkExpression> exprs, int flag) {
		this.format   = format;
		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) {
		List<AwkValue> l = new ArrayList<AwkValue>();
		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 == AwkPrint.APPEND) {
				w = f.getWriter(filename.eval(ns, f).toString(ns));
			} else if(flag == AwkPrint.PIPE) {
				x = new StringWriter();
				w = new PrintLineWriter(new PrintWriter(x));
			} else {
				w = f.openWriter(filename.eval(ns, f).toString(ns));
			}

			for(int i = 0; i < exprs.length; i++) {
				l.add(exprs[i].eval(ns, f));
			}
			w.printf(format.eval(ns, f).toString(ns),
					l.toArray(new Object[0]));
			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();
		}
	}

}
