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

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

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

public class AwkProgram implements AwkExecutable {

	private AwkExecutable[] actions;

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

	public boolean isBegin() {
		for(AwkExecutable e : actions) {
			if(!e.isBegin())  return false;
		}
		return true;
	}

	public boolean isEnd() {
		for(AwkExecutable e : actions) {
			if(!e.isEnd())  return false;
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public boolean isExecuteOnce() {
		for(AwkExecutable e : actions) {
			if(!e.isBegin() && !e.isEnd())  return false;
		}
		return true;
	}

}
