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

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

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

	public AwkPrint(AwkExpression filename,
			List<AwkExpression> exprs, int flag) {
		this.filename = filename;
		this.exprs    = exprs.toArray(new AwkExpression[0]);
		this.flag     = flag;
	}

	@Override
	public AwkValue eval(AwkNamespace ns, AwkFiles f) {
		String ofs = ns.getOFS(), ors = ns.getORS();
		StringWriter x = null;
		PrintWriter 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 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) {
			return AwkValue.FALSE;
		} finally {
			if(w != null)  w.flush();
		}
	}

}
