from errorHandler import outputError, testPrint, indentLevelInc
from listClass import List
from openpyxl.utils import get_column_letter
from pinClass import PinIOType
import globalVariables
from globalVariables import windows, listDict

LOOP_ALL_COMBINATIONS = 1
LOOP_TABLE = 2
LOOP_SIMPLE = 3  # Just a normal loop command


def _gray_encode(n: int):
    """
    This function converts an integer to its gray code equivalent.
    Gray code is made so only 1 bit changes at a time as you count up.
    :param n: int value of number to convert to gray code
    :return: the gray code equivalent of n
    """
    return n ^ n >> 1


class Loop:
    """This class handles loops. It is used so that routines can loop over various combinations of inputs."""

    def __init__(self, rows, iRowStart: int, iCommandIndex: int, worksheetName: str):
        """
        :param rows: rows[iRow][iColumn] is 2D array contain all the cell contents of the present worksheet.
        :param iRowStart: The row of the Excel sheet which has the first line of the loop
        :param iCommandIndex: The index in the commands array that has the first line of the loop
        :param worksheetName: str: The name (title) of the worksheet we are dealing with
        """
        COL_ARG1 = 2  # Column which has the first argument
        COL_COMMAND = 0  # Column which has the command

        self._listDict = {}  # Will contain a dictionary of lists used in the loop.
        self.lists = []  # list of all lists used in the loop
        self._table = []  # Will contain a table of inputs to set and what outputs should be.
        self.successfulInit = False  # Will be set true if we successfully initialize this loop.
        self.loopID = '__' + worksheetName + 'Row' + str(iRowStart + 1)  # Make a unique ID for this
        # loop to append to list
        self._iRowStart = iRowStart  # Save the row number of this loop
        self._iFirstCommandIndex = iCommandIndex  # Save the index of the command that starts this loop
        self._iLastCommandIndex = iCommandIndex  # Save the index of the last command of this loop. This will be
        # updated when the endloop command is processed.
        self._iInstance = 0  # Tracks which item in a list we are executing now
        self._nInstance = 0  # The number of instances we will loop over
        self._iCombination = 0  # When looping over all combination or table entries, tracks which one we are on.
        self._nCombination = 0  # The number of combinations we will loop over.
        # names used in the loop to guarantee the list has a unique name, not shared by some other loop

        # decode the loop type
        loopType = rows[iRowStart][COL_COMMAND]
        if loopType == 'loop':
            self._loopType = LOOP_SIMPLE
        elif loopType == 'loop all combinations':
            self._loopType = LOOP_ALL_COMBINATIONS
        elif loopType == 'loop table':
            self._loopType = LOOP_TABLE
        else:
            outputError(f'Invalid loop type: {loopType}, in row: {iRowStart}. Command will be ignored.')
            self.successfulInit = False
            return

        self.successfulInit = True
        nInputLists = 0  # The number of lists used in the loop command that are inputs (as opposed to outputs)
        nInstance = 1
        # loop over columns in the sheet to find the pin or list of pins we will use in the loop..

        for iColumn in range(COL_ARG1, len(rows[iRowStart])):
            listName = rows[iRowStart][iColumn]
            if listName is None:  # This cell is blank, so there are no more lists
                break
            elif listName[0] == '#':  # This cell has a comment, so there are no more lists
                break
            newList = None
            try:
                # check to see if this is a list from an outer loop. If so, just use it
                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.
                    outName = listName + loopLevel.loopID
                    if outName in listDict:
                        newList = listDict[outName]
                if newList is None:  # This wasn't a list from an outer loop
                    newList = List(rows, iRowStart, iColumn, self.loopID)  # Create a new list.
                self.lists.append(newList)
                if newList.pinIOType == PinIOType.INPUT:  # This is a list of inputs.
                    nInputLists += 1
            except SyntaxError:
                # There was a problem parsing the Excel file. This list will be ignored.
                continue

            nInstance = len(self.lists[0].pinList)  # the length of the first list
            if len(self.lists) > 1:
                if self.lists[0].loopID != self.loopID:  # This list is used in an outer loop and
                    # hence we should only use the current element of it, not the whole list.
                    nInstance = 1
                lenNewList = len(newList.pinList)
                if newList.loopID != self.loopID:  # This list is used in an outer loop
                    lenNewList = 1
                # Make sure this list has the same length as the first list
                if nInstance != lenNewList:
                    testPrint(0, f'Warning: the loop in row: {iRowStart + 1} has lists which are different lengths.'
                                 f' Column: {get_column_letter(COL_ARG1 + 1)}, '
                                 f'list named: {self.lists[0].name}, has '
                                 f'length: {nInstance}. '
                                 f'Column: {get_column_letter(iColumn + 1)}, '
                                 f'list named: {newList.name}, has '
                                 f'length: {lenNewList}. '
                                 f'Loop will iterate for the longest list. Commands trying to use signals past the'
                                 f' end of the shorter lists will be skipped.')

        if len(self.lists) == 0:  # No valid items to loop over were found.
            outputError(f'The loop in row: {iRowStart + 1} has no lists to loop over. Loop will be ignored.')
            self.successfulInit = False
            return

        self._nInstance = nInstance  # save the number of instances that we will loop over.
        if self._loopType == LOOP_SIMPLE:
            self._nCombination = 1
        else:  # looping over all combinations (or a table of combinations)
            self._nCombination = 2 ** nInputLists

        # 'loop table' commands must have a series of 'table' commands after them, specify the values of the
        # inputs and outputs of the loop. Find and save that data now.

        if self._loopType == LOOP_TABLE:  # This loop must have table commands
            for iRow in range(iRowStart + 1, len(rows)):  # loop over remaining rows
                row = rows[iRow]
                command = row[COL_COMMAND]
                if command == 'instance' or command == 'comment':
                    # 'instance' commands happen between the 'loop' nad 'table' commands. Just ignore them.
                    continue
                elif command != 'table':
                    # We must have come to the end of the table
                    break
                else:  # This is a 'table' command
                    tableRow = len(self.lists) * [0]  # initialize all inputs and outputs to 0
                    allColumnsValid = True
                    for iCol in range(len(self.lists)):  # loop over table columns
                        value = row[iCol + COL_ARG1]
                        if value is None:  # the cell is empty
                            continue  # empty cells are treated like a '0'
                        elif value == 1:
                            tableRow[iCol] = 1
                        elif value == 0:
                            continue  # The table is initialized to 0, so no need to do anything
                        else:  # something invalid is in the cell.
                            outputError(f'Cell: {get_column_letter(iCol + COL_ARG1 + 1)}{iRow + 1}, '
                                        f'contains invalid value: {value}. Only "0", "1" and blank cells are '
                                        f'allowed in a table. This row will be ignored.')
                            allColumnsValid = False
                    # end loop over columns
                    if allColumnsValid:
                        self._table.append(tableRow)
            # end loop over row
            self._nCombination = len(self._table)
            if self._nCombination == 0:  # There were no table commands.
                outputError(f'There were no "table" commands in the "loop table" starting on row: {iRowStart + 1}. '
                            f'The "loop table" command will be ignored.')
                self.successfulInit = False

    def start_loop(self, indentLevel, iRow):
        """
        Called to execute a loop command. It sets all the loop variables to their initial values.
        :param indentLevel: Number of spaces to indent the test output
        :param iRow: The row of the Excel sheet which has the start loop command
        :return:
        """
        self._iCombination = 99999
        self._iInstance = -1
        globalVariables.loopCombination = self._iCombination
        # With the above settings, when we call end_loop, it will increment self._iCombination by 1 see it is
        # too large and go on to the next instance by incrementing self._iInstance, making it 0.
        # Which is what they should be for the first time through the loop.
        if self._nInstance == 0:  # This loop is supposed to do zero iterations. So just skip to the end of the loop
            testPrint(indentLevel, 'Loop supposed to iterate over a list of zero length, so nothing will be done.')
            return self._iLastCommandIndex
        else:
            self.end_loop(indentLevel, 999)  # the second argument (iRow) shouldn't be used as the loop should not
        # end on the first attempted iteration.
        return iRow

    def end_loop(self, indentLevel, iRow):
        """
        Called to execute an end loop command. It sets all the loop variable to their next value.
        :param indentLevel: Number of spaces to indent the test output
        :param iRow: The row of the Excel sheet which has the end loop command
        :return: int: the number of the next row that should be executed. It will be iRow + 1 if we are done with
        this loop and self._iStartRow if there are still more iterations to be done.
        """
        # on to next combination
        self._iCombination += 1
        globalVariables.loopCombination = self._iCombination
        if self._iCombination >= self._nCombination:  # We have done the last combination
            # Go on to the next instance.
            self._iCombination = 0
            globalVariables.loopCombination = self._iCombination
            self._iInstance += 1
            if self._iInstance >= self._nInstance:  # We have done our last instance and are through
                for myList in self.lists:
                    if myList.loopID == self.loopID:
                        # Flag that the list is not being used in a loop anymore.
                        myList.loopIndex = -1
                testPrint(indentLevel, f'Ending Loop')
                testPrint(indentLevel, '')  # print a blank line
                return iRow  # should execute next row after the end loop

        testPrint(indentLevel, '')  # print a blank line
        if self._iCombination == 0 and self._iInstance == 0:
            testPrint(indentLevel, f'Starting loop. Combination: {self._iCombination + 1} of {self._nCombination}, '
                                   f'Instance: {self._iInstance + 1} of {self._nInstance}', True)
        else:
            testPrint(indentLevel, f'Proceeding to next loop iteration. Combination: {self._iCombination + 1} '
                                   f'of {self._nCombination}, Instance: {self._iInstance + 1} of '
                                   f'{self._nInstance}', True)
        windows[0].root.title(f'Running test: {windows[0].testNameBeingRun}, '
                              f'Doing loop at Row: {self._iRowStart + 1}, '
                              f'Combination: {self._iCombination + 1} of {self._nCombination}, '
                              f'Instance: {self._iInstance + 1} of {self._nInstance}')

        grayCode = _gray_encode(self._iCombination)
        indentLevel += indentLevelInc
        # grayCode goes through all the possible inputs in a way that only 1 bit changes at a time

        for iList, myList in enumerate(self.lists):
            # Save which instance we are using into each of the lists. That way when set or check commands are
            # executed within the loop, they know which element of the list to use.
            if myList.loopID == self.loopID:
                myList.loopIndex = self._iInstance
            if self._loopType == LOOP_TABLE:
                pin = myList.pinList[myList.loopIndex]  # The present pin to use in this list.
                value = self._table[self._iCombination][iList]
                if pin.pinIOType == PinIOType.INPUT:
                    # Set the input to the value the loop wants
                    pin.setBit(value, indentLevel)
                else:  # It is an output bit, so just save the expected value
                    myList.presentValue = value  # Note we save this to the list, not the pin. This is because if one
                    # checks the pin within the loop, presentValue for the pin gets filled in by checkBit. Then if
                    # later it the loop, one uses the expected valued of the output, there will be a problem. Using
                    # presentValue in the list instead of the pin avoids this problem.
            elif self._loopType == LOOP_ALL_COMBINATIONS:
                pin = myList.pinList[myList.loopIndex]  # The present pin to use in this list.
                if pin.pinIOType == PinIOType.INPUT:
                    value = grayCode & (1 << iList)
                    if value:
                        value = 1
                    # Set the input to the value the loop wants
                    testPrint(indentLevel, f'Setting list: {myList.shortName}, to {value} by doing the following.')
                    pin.setBit(value, indentLevel + indentLevelInc)
        return self._iFirstCommandIndex  # should execute the row after the original loop command
