from orangescape.model.engine.engineconstants import CELL_REF3D,FUNCTION
from orangescape.model.engine.exception.Error import FormulaArgumentError
from orangescape.model.server.util.ServerUtil import operFn_operatorDict
from orangescape.model.engine.exception.ErrorMessage import Engine2024
import logging

def criteriaWalker(sheet,node):
    if node.getNodeType()==FUNCTION:
        nodeValue = node.getNodeValue()
        if nodeValue=='AND' or nodeValue=='OR':
            nodeList = node.getNodeList()
            lhs = nodeList[0]
            rhs = nodeList[1]
            if operFn_operatorDict.__contains__(lhs.getNodeValue()):
                lhs_string= visitCondition(sheet, lhs)
            elif lhs.getNodeType()==FUNCTION:
                lhs_string=criteriaWalker(sheet,lhs)
            if operFn_operatorDict.__contains__(rhs.getNodeValue()):
                rhs_string= visitCondition(sheet, rhs)
            elif lhs.getNodeType()==FUNCTION:
                rhs_string=criteriaWalker(sheet,operatorNode)
            condition_string='('+lhs_string+' '+nodeValue+' '+rhs_string+')'
            return condition_string
        elif operFn_operatorDict.__contains__(nodeValue):
               return visitCondition(sheet, node)
        else:
            logging.info('Unsupported nodevalue in criteria %s'%(node.getNodeType()))
    else:
        raise Exception('Unsupported nodetype in criteria %s'%(node.getNodeType()))

def visitCondition(sheet,operatorNode):
    operatorValue = operatorNode.getNodeValue()
    if operFn_operatorDict.__contains__(operatorValue):
        nodeList = operatorNode.getNodeList()
        lhsNode = nodeList[0]
        rhsNode = nodeList[1]
        if lhsNode.getNodeType()==CELL_REF3D:
            if rhsNode.isString():
                rhsValue = rhsNode.getNodeValue()
            else:
                rhsValue = rhsNode.getNodeFloatValue()
            return '('+lhsNode.getCellMetadata().getSheetId()+operFn_operatorDict[operatorNode.getNodeValue()]+rhsValue+')'
        else:
            raise FormulaArgumentError, Engine2024% (sheet.getSheetMetadata().getSheetName(), getFormulaContainer(getFormula(lhsNode)))
