/*
 * JaamSim Discrete Event Simulation
 * Copyright (C) 2014 Ausenco Engineering Canada Inc.
 * Copyright (C) 2016-2018 JaamSim Software Inc.
 *
 * 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 com.jaamsim.input;

import java.util.ArrayList;

import com.jaamsim.basicsim.Entity;
import com.jaamsim.input.ExpParser.Expression;

public class ExpressionInput extends Input<ExpParser.Expression> {
	private Entity thisEnt;
	private ExpEvaluator.EntityParseContext parseContext;

	public ExpressionInput(String key, String cat, ExpParser.Expression def) {
		super(key, cat, def);
	}

	public void setEntity(Entity ent) {
		thisEnt = ent;
	}

	@Override
	public void copyFrom(Input<?> in) {
		super.copyFrom(in);

		// An expression input must be re-parsed to reset the entity referred to by "this"
		parseFrom(in);
	}

	@Override
	public String applyConditioning(String str) {
		return Parser.addQuotesIfNeeded(str);
	}

	@Override
	public void parse(KeywordIndex kw)
	throws InputErrorException {
		Input.assertCount(kw, 1);
		try {
			String expString = kw.getArg(0);

			ExpEvaluator.EntityParseContext pc = ExpEvaluator.getParseContext(thisEnt, expString);
			Expression exp = ExpParser.parseExpression(pc, expString);

			// Save the expression
			parseContext = pc;
			value = exp;

		} catch (ExpError e) {
			throw new InputErrorException(e);
		}
	}

	@Override
	public String getValidInputDesc() {
		return Input.VALID_EXP;
	}

	@Override
	public void getValueTokens(ArrayList<String> toks) {
		if (value == null) return;
		toks.add(parseContext.getUpdatedSource());
	}

	@Override
	public boolean useExpressionBuilder() {
		return true;
	}

}

@@ -837,16 +837,47 @@
 ression;
+%0Aimport com.jaamsim.units.Unit;
 %0A%0Apublic
@@ -937,16 +937,57 @@
 sion%3E %7B%0A
+%09private Class%3C? extends Unit%3E unitType;%0A
 %09private
@@ -1163,16 +1163,219 @@
 f);%0A%09%7D%0A%0A
+%09public void setUnitType(Class%3C? extends Unit%3E u) %7B%0A%09%09if (u == unitType) %7B%0A%09%09%09return;%0A%09%09%7D%0A%09%09unitType = u;%0A%09%09this.setValid(false);%0A%09%7D%0A%0A%09public Class%3C? extends Unit%3E getUnitType() %7B%0A%09%09return unitType;%0A%09%7D%0A%0A
 %09public 
@@ -2004,16 +2004,60 @@
 String);
+%0A%09%09%09ExpParser.assertUnitType(exp, unitType);
 %0A%0A%09%09%09// 
@@ -2098,16 +2098,16 @@
 t = pc;%0A
-
 %09%09%09value
@@ -2113,16 +2113,40 @@
 e = exp;
+%0A%09%09%09this.setValid(true);
 %0A%0A%09%09%7D ca

add unit type to ExpressionInput