/***********************************************
* Columbia University CS Department
* Network Security Lab
*
* Open and Survivable Embedded Systems (OASES)
*
* Structured Policy Command Language (SPCL)
*
*
* This software is provided as is without any
* warranty or guarantee of merchantibility
* or fitness for a particular purpose. This
* software is released under the terms of the
* GNU General Public License (GPL).
*
* Last updated: May 9, 2003
*
***********************************************/

package spcl.data;


/**
 * The condition class represents something for the
 *  PolicyEngine to unify with the current params
 *  in a query.
 *
 * A Condition is a boolean expression: 
 *   [ variable relop rval ]
 *   [ channel == 5 ]
 *
 * whereas a param is a name/value pair:
 *   channel/7
 *
 * This needs to be unified during the search.
 *
 * @author locasto@cs.columbia.edu
*/
public class Condition{

  public Variable var;
  public String relop;
  public boolean b_rval;
  public String rval;

  public Condition( Variable var, String relOp, boolean rval ){
    this.var = var;
    this.relop = relOp;
    this.b_rval = rval;
  }

  public Condition( Variable var, String relOp, String rval ){
    this.var = var;
    this.relop = relOp;
    this.rval = rval;
  }

  public boolean eval(){
	int nval;
    switch( var.getType() ){
		case Variable.NUMBER:
			//all relops
			try{nval = Integer.parseInt( rval );
			}catch( NumberFormatException nfex ){ return false; }
			if( relop.equals( "==" ) ){
				return (nval==var.getNumberValue());
			}else if( relop.equals( "!=" ) ){
				return (nval!=var.getNumberValue());
			}else if( relop.equals( ">" ) ){
				return (var.getNumberValue()>nval);
			}else if( relop.equals( "<" ) ){
				return (var.getNumberValue()<nval);
			}else if( relop.equals( ">=" ) ){
				return (var.getNumberValue()>=nval);
			}else if( relop.equals( "<=" ) ){
				return (var.getNumberValue()<=nval);
			}else{
				return false;
			}
		case Variable.STRING:
			//only != and ==
			if( relop.equals( "==" ) ){
			    return (rval.equals(var.getStringValue()));
			}else if( relop.equals( "!=" ) ){
				return (!rval.equals(var.getStringValue()));
			}else{
				return false;
			}
		case Variable.BOOLEAN:
			//only != and ==
			if( relop.equals( "==" ) ){
			    return (b_rval==var.getBooleanValue());
			}else if( relop.equals( "!=" ) ){
				return (b_rval!=var.getBooleanValue());
			}else{
				return false;
			}
	}
	return false;
  }

  public String toString(){
  	return (var.toString()+relop+rval);
  }
}
