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

import java.math.BigInteger;
import java.util.Collection;

import net.morilib.awk.nano.io.AwkFiles;
import net.morilib.awk.nano.namespace.AwkNamespace;
import net.morilib.awk.nano.value.AwkInteger;
import net.morilib.awk.nano.value.AwkValue;

/**
 * awkiumのプログラム全体を現すクラスです。
 * 
 * @author MORIGUCHI, Yuichiro 2013/03
 */
public class AwkProgram implements AwkExecutable {

	private AwkExecutable[] actions;

	/**
	 * awkiumプログラムを生成します。
	 * 
	 * @param actions アクションの集合
	 */
	public AwkProgram(Collection<AwkExecutable> actions) {
		this.actions = actions.toArray(new AwkExecutable[0]);
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.code.AwkExecutable#execute(java.lang.String)
	 */
	public void execute(AwkNamespace ns, AwkFiles f, String s) {
		AwkValue v;
		BigInteger b;

		v = ns.find("NR");
		b = v != null ? v.toInteger() : BigInteger.ZERO;
		b = b.add(BigInteger.ONE);
		v = ns.find("FNR");
		b = v != null ? v.toInteger() : BigInteger.ZERO;
		b = b.add(BigInteger.ONE);
		for(AwkExecutable e : actions) {
			ns.setField(s);
			ns.assign("NR", AwkInteger.valueOf(b));
			ns.assign("FNR", AwkInteger.valueOf(b));
			e.execute(ns, f, s);
		}
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.code.AwkExecutable#executeBegin(net.morilib.awk.namespace.AwkNamespace, net.morilib.awk.io.AwkFiles)
	 */
	public void executeBegin(AwkNamespace ns, AwkFiles f) {
		for(AwkExecutable e : actions) {
			e.executeBegin(ns, f);
		}
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.code.AwkExecutable#executeEnd(net.morilib.awk.namespace.AwkNamespace, net.morilib.awk.io.AwkFiles)
	 */
	public void executeEnd(AwkNamespace ns, AwkFiles f) {
		for(AwkExecutable e : actions) {
			e.executeEnd(ns, f);
		}
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.code.AwkExecutable#isBegin()
	 */
	public boolean isBegin() {
		for(AwkExecutable e : actions) {
			if(!e.isBegin())  return false;
		}
		return true;
	}

	/* (non-Javadoc)
	 * @see net.morilib.awk.code.AwkExecutable#isEnd()
	 */
	public boolean isEnd() {
		for(AwkExecutable e : actions) {
			if(!e.isEnd())  return false;
		}
		return true;
	}

	/**
	 * BEGINとEND以外のアクションを含まないときtrueを得ます。
	 */
	public boolean isExecuteOnce() {
		for(AwkExecutable e : actions) {
			if(!e.isBegin())  return false;
		}
		return true;
	}

}
