/*
 * JaamSim Discrete Event Simulation
 * Copyright (C) 2014 Ausenco Engineering Canada Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
package com.jaamsim.Thresholds;

import com.jaamsim.events.ConditionalHandle;
import com.jaamsim.input.ExpEvaluator;
import com.jaamsim.input.ExpressionInput;
import com.jaamsim.input.Keyword;
import com.sandwell.JavaSimulation.InputErrorException;

public class ExpressionThreshold extends Threshold {

	@Keyword(description = "The logical condition for which the Threshold is open.",
	         example = "ExpressionThreshold1  OpenCondition { '[Queue1].QueueLength < 3' }")
	private final ExpressionInput openCondition;

	{
		openCondition = new ExpressionInput("OpenCondition", "Key Inputs", null);
		this.addInput(openCondition);
	}

	@Override
	public void validate() throws InputErrorException {
		super.validate();

		if (openCondition == null)
			throw new InputErrorException( "The keyword OpenCondition must be set." );
	}

	@Override
    public void startUp() {
		super.startUp();
		doOpenClose();
	}

	private void doOpenClose() {

		// Set the present state
		closed = !this.getOpenConditionValue(this.getSimTime());

		// Loop endlessly
		ConditionalHandle h = new ConditionalHandle();
		while (true) {

			// Wait until the state has changed
			while( this.getOpenConditionValue(this.getSimTime()) != closed ) {
				waitUntil(h);
			}
			waitUntilEnded();

			// Set the present state
			closed = !this.getOpenConditionValue(this.getSimTime());

			// Notify the users of this threshold
			this.scheduleChangedCallback();
		}
	}

	private boolean getOpenConditionValue(double simTime) {
		try {
			// Evaluate the condition (0 = false, non-zero = true)
			boolean ret = ExpEvaluator.evaluateExpression(openCondition.getValue(), simTime, this, null).value != 0;
			return ret;
		} catch(ExpEvaluator.Error e) {
			throw new RuntimeException(e);
		}
	}

}

@@ -632,53 +632,8 @@
 s;%0A%0A
-import com.jaamsim.events.ConditionalHandle;%0A
 impo
@@ -1605,57 +1605,8 @@
 sly%0A
-%09%09ConditionalHandle h = new ConditionalHandle();%0A
 %09%09wh
@@ -1742,17 +1742,16 @@
 itUntil(
-h
 );%0A%09%09%09%7D%0A

remove the unused conditonal handle