/* $Id: RelationalExpression.java,v 1.2 2007/11/05 09:50:54 nito Exp $
 * 
 * Copyright (c)ARGO 21, Corporation. 2005, 2006.  All rights reserved.
 * 
 * This file is part of Nautica Workflow Core.
 * 
 *  Nautica Workflow Core is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation; either version 2.1 of the License, or
 *  (at your option) any later version.
 * 
 *  Nautica Workflow Core 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 Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Nautica Workflow Core; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *  
 */
package jp.co.argo21.nautica.workflow.expression;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import jp.co.argo21.nautica.workflow.dataaccess.VariableBean;
import jp.co.argo21.nautica.workflow.definition.VariableDefinition;
import jp.co.argo21.nautica.workflow.xpdl.RelationalExpressionDocument;

import org.apache.xmlbeans.XmlObject;

/**
 * 関係条件式
 * 
 * @author  Norihiro Itoh(ARGO 21 Corp.)
 * @version $Revision: 1.2 $
 * @since   Nautica Workflow 1.0
 */
public class RelationalExpression implements Expression
{
	/** シリアルバージョンUID */
	private static final long serialVersionUID = 20050000000000001L;

	/** == */
	public static final int EQUAL         = RelationalExpressionDocument.RelationalExpression.Type.INT_EQUAL;
	/** != */
	public static final int NOT_EQUAL     = RelationalExpressionDocument.RelationalExpression.Type.INT_NOT_EQUAL;
	/** < */
	public static final int LESS_THAN     = RelationalExpressionDocument.RelationalExpression.Type.INT_LESS_THAN;
	/** <= */
	public static final int LESS_EQUAL    = RelationalExpressionDocument.RelationalExpression.Type.INT_LESS_EQUAL;
	/** > */
	public static final int GREATER_THAN  = RelationalExpressionDocument.RelationalExpression.Type.INT_GREATER_THAN;
	/** >= */
	public static final int GREATER_EQUAL = RelationalExpressionDocument.RelationalExpression.Type.INT_GREATER_EQUAL;

	/** == */
	private static final String EQUAL_STR         = "==";
	/** != */
	private static final String NOT_EQUAL_STR     = "!=";
	/** < */
	private static final String LESS_THAN_STR     = "<";
	/** <= */
	private static final String LESS_EQUAL_STR    = "<=";
	/** > */
	private static final String GREATER_THAN_STR  = ">";
	/** >= */
	private static final String GREATER_EQUAL_STR = ">=";

	/** 演算子 */
	private int operator;
	/** 左辺値 */
	private String leftValue;
	/** 右辺値 */
	private String rightValue;
	
	/**
	 * 関係条件式を生成する。
	 * 
	 * @param lVal	左辺値
	 * @param ope	演算子
	 * @param rVal	右辺値
	 */
	public RelationalExpression(String lVal, int ope, String rVal)
	{
		operator = ope;
		leftValue = lVal;
		rightValue = rVal;
	}
	
	/**
	 * XMLから関係条件式を生成する。
	 * 
	 * @param exp	XML
	 */
	public RelationalExpression(RelationalExpressionDocument.RelationalExpression exp)
	{
		operator = exp.getType().intValue();
		leftValue = exp.getDataFieldRef();
		rightValue = exp.getComparedValue();
	}
	
	/**
	 * 引数のオブジェクトに条件式を格納する。
	 * 
	 * @param o	XMLオブジェクト
	 * @see jp.co.argo21.nautica.workflow.expression.Expression#saveTo(org.apache.xmlbeans.XmlObject)
	 */
	public void saveTo(XmlObject o)
	{
		if (o == null) return;
		if (!(o instanceof RelationalExpressionDocument.RelationalExpression)) return;

		RelationalExpressionDocument.RelationalExpression re
			= (RelationalExpressionDocument.RelationalExpression)o;

		re.setType(RelationalExpressionDocument.RelationalExpression.Type.Enum.forInt(operator));
		if (leftValue != null) re.setDataFieldRef(leftValue);
		if (rightValue != null) re.setComparedValue(rightValue);
	}

	/**
	 * 引数の情報を元に条件を評価する。
	 * 
	 * @param list	変数の現在値
	 * @return	条件が満たされた場合はtrue
	 * @see jp.co.argo21.nautica.workflow.expression.Expression#eval(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public boolean eval(List list)
	{
		VariableBean var = getVariable(list, leftValue);

		if (var == null) return false;
		
		int type = var.getType();
		String value = var.getValue();
		if (type == VariableDefinition.BOOLEAN) {
			return evalAsBoolean(value, rightValue);
		} else if (type == VariableDefinition.INTEGER) {
			return evalAsInteger(value, rightValue);
		} else {
			return evalAsString(value, rightValue);
		}
	}

	/**
	 * 条件式の文字列表現を返す。
	 * 
	 * 
	 * @return	文字列表現
	 * @see jp.co.argo21.nautica.workflow.expression.Expression#getExpressionString()
	 */
	public String getExpressionString()
	{
		String ls = "null";
		String rs = "null";
		if (leftValue != null) ls = leftValue;
		if (rightValue != null) rs = rightValue;
		
		return "(" + ls +  ") " + getOpeString() + " (" + rs + ")";
	}

	/**
	 * 変数一覧を利用しながら条件式の文字列表現を返す。
	 * 
	 * @param vars	変数一覧
	 * @return	文字列表現
	 * @see jp.co.argo21.nautica.workflow.expression.Expression#getExpressionString(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public String getExpressionString(List vars)
	{
		if (vars == null) return getExpressionString();
		if (leftValue == null) return getExpressionString();
		
		String label = null;
		for (Object o : vars) {
			if (o == null) continue;
			if (!(o instanceof VariableDefinition)) continue;

			if (((VariableDefinition)o).getID().equals(leftValue)) {
				label = ((VariableDefinition)o).getName();
				break;
			}
		}
		String ls = "null";
		String rs = "null";
		if (label != null) ls = label;
		if (rightValue != null) rs = rightValue;
		
		return "(" + ls +  ") " + getOpeString() + " (" + rs + ")";
	}

	/**
	 * この条件式に含まれるすべての条件式を返す。
	 * 
	 * @param exps	条件式一覧
	 * @see jp.co.argo21.nautica.workflow.expression.Expression#getAllExpressions(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	public void getAllExpressions(List exps)
	{
		if (exps.contains(this) == false) exps.add(this);
	}

	/**
	 * 演算子の文字列表現を返す。
	 * 
	 * @return	文字列表現
	 */	
	private String getOpeString()
	{
		if (operator == NOT_EQUAL) return NOT_EQUAL_STR;
		else if (operator == LESS_THAN) return LESS_THAN_STR;
		else if (operator == LESS_EQUAL) return LESS_EQUAL_STR;
		else if (operator == GREATER_THAN) return GREATER_THAN_STR;
		else if (operator == GREATER_EQUAL) return GREATER_EQUAL_STR;
		else return EQUAL_STR;
	}

	/**
	 * 条件を真理値として評価する。
	 * 
	 * @param v1	左辺値
	 * @param v2	右辺値
	 * @return	評価結果
	 */
	private boolean evalAsBoolean(String v1, String v2)
	{
		boolean result = false;
		Boolean b1 = null;
		Boolean b2 = null;
		try { b1 = new Boolean(v1); } catch (Exception ex) {}
		try { b2 = new Boolean(v2); } catch (Exception ex) {}

		if (b1 == null) return false;
		if (b2 == null) return false;

		result = b1.equals(b2);

		if (operator == EQUAL) return result;		
		else return (! result);
	}

	/**
	 * 条件を日付として評価する。
	 * 
	 * @param v1	左辺値
	 * @param v2	右辺値
	 * @return	評価結果
	 */
	@SuppressWarnings("unused")
	private boolean evalAsDateTime(String v1, String v2)
	{
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(v1);
		} catch (Exception ex) {
			return false;
		}

		try {
			d2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(v2);
		} catch (Exception ex) {
			return false;
		}

		return evalComparedValue(d1.compareTo(d2));
	}

	/**
	 * 条件を整数として評価する。
	 * 
	 * @param v1	左辺値
	 * @param v2	右辺値
	 * @return	評価結果
	 */
	private boolean evalAsInteger(String v1, String v2)
	{
		BigInteger i1 = null;
		BigInteger i2 = null;
		try {
			i1 = new BigInteger(v1);
		} catch (Exception ex) {
			return false;
		}

		try {
			i2 = new BigInteger(v2);
		} catch (Exception ex) {
			return false;
		}

		return evalComparedValue(i1.compareTo(i2));
	}

	/**
	 * 条件を実数として評価する。
	 * 
	 * @param v1	左辺値
	 * @param v2	右辺値
	 * @return	評価結果
	 */
	@SuppressWarnings("unused")
	private boolean evalAsDecimal(String v1, String v2)
	{
		BigDecimal d1 = null;
		BigDecimal d2 = null;
		try {
			d1 = new BigDecimal(v1);
		} catch (Exception ex) {
			return false;
		}

		try {
			d2 = new BigDecimal(v2);
		} catch (Exception ex) {
			return false;
		}

		return evalComparedValue(d1.compareTo(d2));
	}

	/**
	 * 数値の比較結果を判定する。
	 * 
	 * @param comp	比較結果
	 * @return	判定
	 */	
	private boolean evalComparedValue(int comp)
	{
		if (comp < 0) {
			if (operator == LESS_THAN
			  || operator == LESS_EQUAL
			  || operator == NOT_EQUAL) {
				return true;
			} else {
				return false;
			}
		} else if (comp > 0) {
			if (operator == GREATER_THAN
			  || operator == GREATER_EQUAL
			  || operator == NOT_EQUAL) {
				return true;
			} else {
				return false;
			}
		} else { 
			if (operator == EQUAL
			  || operator == LESS_EQUAL
			  || operator == GREATER_EQUAL) {
				return true;
			} else {
				return false;
			}
		}
	}

	/**
	 * 条件を文字列として評価する。
	 * 
	 * @param v1	左辺値
	 * @param v2	右辺値
	 * @return	評価結果
	 */
	private boolean evalAsString(String v1, String v2)
	{
		boolean result = false;
		if (v1 == null && v2 == null) result = true;
		else if (v1 == null) result = false;
		else if (v2 == null) result = false;
		else result = v1.equals(v2);

		if (operator == EQUAL) return result;		
		else return (! result);
	}

	/**
	 * 変数を返す。
	 * 
	 * @param list	変数一覧
	 * @param id	変数ID
	 * @return	変数
	 */
	@SuppressWarnings("unchecked")
	private VariableBean getVariable(List list, String id)
	{
		Iterator it = list.iterator();
		
		while (it.hasNext()) {
			VariableBean v = (VariableBean)it.next();
			if (id.equals(v.getVariableDefinitionID())) return v;
		}
		return null;
	}
}
