#include "__if.h"
#include "Exception.h"
#include <iostream>
#include "Operand.h"

namespace jet {

   __if::__if(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this, "else") {
      coreutils::MString result;
      bool booleanResult = false;
      if(keywordDefined("value1")) {
	 if(keywordDefined("expr"))
	   throw coreutils::Exception("Either value1 or expr can be specified but not both.");
	 if(keywordDefined("value2")) {
	    if(!keywordDefined("type")) 
	      throw coreutils::Exception("type expected if value1 and value2 specified.");
	 } else
	   throw coreutils::Exception("value2 required if value1 specified.");
	 coreutils::MString type = resolveKeyword("type");
	 if((type != "eq") &&
	    (type != "ne") &&
	    (type != "lt") &&
	    (type != "le") &&
	    (type != "gt") &&
	    (type != "ge"))
	   throw coreutils::Exception("type value must be 'eq','ne','lt','le','gt','ge'.");	   
	 int rc = resolveKeyword("value1").compare(resolveKeyword("value2"));
//	 std::cout << "if: " << resolveKeyword("value1") << " " << type << " " << resolveKeyword("value2") << ":" << rc << std::endl;
	 if(((type == "eq") && (rc == 0)) ||
	    ((type == "ne") && (rc != 0)) ||
	    ((type == "lt") && (rc == -1)) || 
	    ((type == "le") && (rc != 1)) ||
	    ((type == "gt") && (rc == 1)) ||
	    ((type == "ge") && (rc != -1)))
	   booleanResult = true;
	 else
	   booleanResult = false;
      } else if(keywordDefined("expr")) {
	 if(keywordDefined("value2"))
	   throw coreutils::Exception("value2 should not be specified with expr.");
	 if(keywordDefined("type"))
	   throw coreutils::Exception("type should not be specified with expr.");
	 booleanResult = Operand(keywords["expr"], *this).boolean;
      }
      if(booleanResult) 
	processContainer(container);
      else if(hasContainer2)
	processContainer(container2);
   }

}
