from errorHandler import outputError
import globalVariables
from globalVariables import loopStack, listDict, variableDict, pinDict
from variableClass import Variable
from openpyxl.utils import get_column_letter
from pyEval import Parser
from pinClass import PinIOType, Pin
from listClass import List

CMD_SET = 1
CMD_CHECK_EXPR = 2


class Expr:
    """This class handles expressions. It is used for the 'variable set' and 'check expr' commands.
    Expressions are of the form:  varName = x and y or not z"""

    def __init__(self, row, iRow):
        """
        :param row: List contain the cell values of the row that has the expression
        :param iRow: The row number that has the expression
        """
        COL_ARG1 = 2  # Column which has the first argument
        COL_COMMAND = 0  # Column which has the command
        self.parser = Parser()  # Create parser object which will be used to parse the expression
        self.presentValue = 0  # The present output of the expression.
        self.inObjects = []  # Will contain the pin, variable  or list objects that are used on the expression
        self._firstIterOnly = False
        # right side of the '='

        # Two types of commands 'check expr' and 'variable set' have an expression for their first argument.
        # These get handled slightly differently. So, save which type of command we are dealing with.
        command = row[COL_COMMAND]
        if command == 'check expr':
            self._command = CMD_CHECK_EXPR
        elif command == 'variable set':
            self._command = CMD_SET
        elif command == 'variable set if first loop iteration':
            self._command = CMD_SET
            self._firstIterOnly = True
            # This command is only allowed inside a loop. Complain if otherwise.
            if len(loopStack) == 0:
                outputError(f'The command: {command}, in row: {iRow + 1}, must be inside a loop. '
                            f'Command will be ignored.')
                raise SyntaxError
        else:
            outputError(f'Bug: Class: Expr, called with an invalid command in '
                        f'cell: {get_column_letter(COL_ARG1 + 1)}{iRow + 1}. Contact author of the program to fix.')
            raise SyntaxError

        expression = row[COL_ARG1]
        out_in = expression.split('=')  # Split the string into 2 pieces at the equals sign

        if len(out_in) != 2:
            outputError(f'There is an invalid expression: {expression}, '
                        f'in cell {get_column_letter(COL_ARG1 + 1)}{iRow + 1}.'
                        f' It must contain exactly 1 equals sign.')
            raise SyntaxError('Problem parsing Excel file')

        outObject = None  # Will later be set to the variable or pin object that is to the left of the '='..
        outputName = out_in[0].replace(' ', '')  # remove all spaces
        if self._command == CMD_CHECK_EXPR:
            # It must be a pinName or a listName
            if outputName in pinDict:
                outObject = pinDict[outputName]
            elif outputName in listDict:
                outObject = listDict[outputName]
                for loopLevel in globalVariables.loopStack:  # loop over all levels of loop we may be in
                    # When list is created as part of the loop command, it has suffix to make the name unique.
                    # That gets priority over a simple list.
                    outName = outputName + loopLevel.loopID
                    if outName in listDict:
                        outObject = listDict[outName]
            if outObject is not None:
                if outObject.pinIOType != PinIOType.OUTPUT:
                    outputError(f'The "check expr" command in row: {iRow + 1}, tries to check an input: {outputName}. '
                                f'You can only check an output. Command will be ignored.')
                    raise SyntaxError('Problem parsing Excel file')

        else:  # The command must be 'variable set'' and hence have a variableName to the left of the equal sign
            if outputName in variableDict:
                outObject = variableDict[outputName]
            else:  # create a new variable
                outObject = Variable(outputName, iRow + 1)
                variableDict[outputName] = outObject
        # end if self._command == CMD_CHECK_EXPR:

        if outObject is None:  # The name on the left of the equal sign doesn't exist
            outputError(f'The name to the left of the equals sign: {outputName}, is not a signal, '
                        f'list or loop variable name.'
                        f' Row {iRow + 1} will be ignored.')
            raise SyntaxError('Problem parsing Excel file')

        # Now decode the expression to the right of the equals sign.
        self.outObject = outObject  # Save the object to the left of the equals sign.

        # Now parse the expression to the right of the equals sign
        try:
            expression = out_in[1].replace('!', 'not ')  # parser doesn't know that "!" means "not", so replace it.
            self.parsed = self.parser.parse(expression)
        except SyntaxError as ex:
            outputError(f'Cell: {get_column_letter(COL_ARG1 + 1)}{iRow + 1}, '
                        f'has invalid expression: {expression}. {ex.args[0]}. '
                        f'Command will be ignored')
            raise SyntaxError('Problem parsing Excel file')
        newInputNames = self.parsed.variables()  # get the variable names from the parser
        # Save the pins, variables and lists used for the inputs to the expression (to the right of the equals sign)
        # Inside a loop, it can be a list used by the loop or a variable or a pin.
        # Outside a loop, it can only be a variable or a pin or a list of length 1
        for newInputName in newInputNames:
            inObject = None  # Will later be set to the variable or pin or list object with name newInputName.
            for loopLevel in globalVariables.loopStack:  # loop over all levels of loop we may be in
                # When list is created as part of the loop command, it has suffix to make the name unique.
                # Check for that first.
                inName = newInputName + loopLevel.loopID
                if inName in listDict:
                    inObject = listDict[inName]
                    self.inObjects.append(inObject)
            if inObject is not None:
                continue  # skip to end of loop as we have found this name.
            # check for names that can occur inside or outside loops
            # It must be a pinName or variable name or a list of length 1
            if newInputName in pinDict:
                inObject = pinDict[newInputName]
                if inObject.pinIOType != PinIOType.INPUT:
                    outputError(
                        f'The "check expr" command in row: {iRow + 1}, tries to use an output: {newInputName}. '
                        f'You can only use inputs to the right of the equals sign. Command will be ignored.')
                    raise SyntaxError('Problem parsing Excel file')
            elif newInputName in variableDict:
                inObject = variableDict[newInputName]
            elif newInputName in listDict:
                myList = listDict[newInputName]
                listLength = len(myList.pinList)
                if listLength != 1:
                    outputError(f'The list: {newInputName}, must have a length of one to use it in an expression. '
                                f'It has a length of {listLength}. '
                                f'Row {iRow + 1} will be ignored.')
                else:
                    inObject = myList
                    if inObject.pinList[0].pinIOType != PinIOType.INPUT:
                        outputError(
                            f'The "check expr" command in row: {iRow + 1}, tries to use an output: {newInputName}. '
                            f'You can only use inputs to the right of the equals sign. Command will be ignored.')
                        raise SyntaxError('Problem parsing Excel file')

            if inObject is None:  # The name was not found
                outputError(
                    f'The name: {newInputName}, is a not pin, variable, list of length 1 or loop variable name.'
                    f' Row {iRow + 1} will be ignored.')
                raise SyntaxError('Problem parsing Excel file')
            else:
                self.inObjects.append(inObject)

    def evaluate(self, indentLevel: int):
        """
        This routine evaluates the expression and saves the results to the item on the left hand side of the
        equals sign
        :return:
        """
        expressionInputs = {}
        # get all the inputs to the expression
        for i, inObject in enumerate(self.inObjects):
            inObjectName = 'junk'  # This should always get overwritten. It is here to avoid compiler warning message
            if isinstance(inObject, List):  # inObject is a list
                # use the name that doesn't have the loopID appended to it.
                inObjectName = inObject.shortName
                if inObject.loopIndex >= 0:  # A loop is iterating through this list.
                    if inObject.pinIOType == PinIOType.INPUT:
                        if inObject.loopIndex >= len(inObject.pinList):
                            # The loop has gone past the end of this list, so do nothing.
                            return None
                        # Just set the current pin in the list.
                        inObject = inObject.pinList[inObject.loopIndex]
                    # Note when inObject is a list of OUTPUT pins, we leave it pointing to the list and not a pin.
                else:  # We are not iterating though a list. Just use the first element of the list
                    inObject = inObject.pinList[0]
            elif isinstance(inObject, Pin) or isinstance(inObject, Variable):  # it is a Variable or a Pin object.
                inObjectName = inObject.name

            expressionInputs[inObjectName] = inObject.presentValue

        self.presentValue = self.parsed.evaluate(expressionInputs)  # evaluate the expression
        if self.presentValue:
            self.presentValue = 1
        else:
            self.presentValue = 0

        if self._firstIterOnly and globalVariables.loopCombination > 0:
            pass  # Do nothing since we are only supposed to save the result for the first iteration of a loop.
        else:
            if self._command == CMD_SET:
                # Save the result to the object on the left side of the equals sign.
                self.outObject.setBit(self.presentValue, indentLevel)
                return None
            else:  # We are doing a check
                # The calling routine will do the actual check. Just return the expected answer
                return self.presentValue
                # self.outObject.checkBit(self.presentValue, indentLevel)
