from openpyxl.utils import get_column_letter

from errorHandler import outputError, indentLevelInc, testPrint
import globalVariables
from globalVariables import pinDict, listDict


class List:
    """This class handles lists of pins. It is used so that routines can loop over all the pins in a list."""

    def __init__(self, rows, iRowStart: int, iColumn: int, loopID=''):
        """
        Create a list from information in the spreadsheet.
        :param rows: rows[iRow][iColumn] is 2D array contain all the cell contents of the present worksheet.
        :param iRowStart: The row that the list starts in. This row will have the name of the list and following
                            rows will have the signalNames in the list
        :param iColumn: The column in the sheet that has the list
        :param loopID: Optional argument. If non-blank, the list starts on a line with a loop statement.
                         The loopID string will be appended to the listName that comes form iRowStart. In this
                         case, all items in the list must be in rows that have "instance" in the first column.
        """
        self.pinList = []  # Will contain the list of signals/pins in this list
        listName = rows[iRowStart][iColumn]
        nextCommand = rows[iRowStart + 1][0]
        self.loopID = loopID
        self.name = listName + loopID
        self.pinIOType = 'junk'  # will be filled in later
        self.shortName = listName
        self.loopIndex = -1  # When this list is used in a loop, this will be set to index of the element we are using.
        self.presentValue = 2  # When this list is used in a loop table, the correct value of the outputs
        # will be kept here. Setting it to 2 flags it as uninitialized.
        if self.name in listDict:
            outputError(
                f'List named: {listName}, starting in cell: {get_column_letter(iColumn + 1)}{iRowStart + 1}, '
                f'has previously been defined. This new list will be ignored.')
            raise SyntaxError

        if loopID != '' and nextCommand is not None and nextCommand != 'instance':
            # This is single item list in a loop definition as there are no 'instance' commands following it.
            # That item should either be a pin name or a list name. If the former, we will create a 1 item list.
            # If the latter, we will copy the items from the specified list to this list.
            inObject = None
            # Check to see if this is listName that is used in a loop.
            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 = listName + loopLevel.loopID
                if inName in listDict:
                    inObject = listDict[inName]
            if inObject is not None:  # This was a list that a loop is looping over, so we save the list
                self.pinList.append(inObject.pinList[inObject.loopIndex])
            elif listName in pinDict:
                pin = pinDict[listName]
                self.pinList.append(pin)
            elif listName in listDict:
                myList = listDict[listName]
                for pin in myList.pinList:
                    self.pinList.append(pin)
            else:
                outputError(f'The pin or signal name: {listName}, '
                            f'in cell: {get_column_letter(iColumn + 1)}{iRowStart + 1}, has not been defined. '
                            f'It will be ignored.')
                raise SyntaxError

        else:
            firstRow = iRowStart + 1
            # firstRow now is the row that has the first item of the list.

            for iRow in range(firstRow, len(rows)):  # loop over all rows with signal names
                if loopID != '':  # The list is defined in a loop. So, quit if there is not 'instance' in column 1
                    command = rows[iRow][0]
                    if command is None:  # cell is empty, so skip this row
                        continue
                    elif command == 'comment':  # The command is a comment, so skip this row
                        continue
                    elif command != 'instance':  # we are done
                        break
                signalName = rows[iRow][iColumn]
                if signalName is None:  # cell is empty, so we are done
                    break

                if signalName in pinDict:
                    pin = pinDict[signalName]
                    if len(self.pinList) > 0:
                        # Require all elements in the list to have same pinIOType
                        if pin.pinIOType != self.pinList[0].pinIOType:
                            outputError(f'List members must all be input pins or all output pins. '
                                        f'The signalName: {signalName}, in cell: '
                                        f'{get_column_letter(iColumn + 1)}{iRow + 1}, '
                                        f'is an: {pin.pinIOType.name}, while '
                                        f'the signalName: {self.pinList[0].signalName}, '
                                        f'in cell: {get_column_letter(iColumn + 1)}{firstRow + 1}, '
                                        f'is an: {self.pinList[0].pinIOType.name}, '
                                        f'This signalName will not be added to the list.')
                            continue
                    self.pinList.append(pin)
                elif signalName in listDict:
                    myList = listDict[signalName]
                    if len(self.pinList) > 0 and len(myList.pinList) > 0:
                        # Require all elements in the list to have same pinIOType
                        if myList.pinIOType != self.pinList[0].pinIOType:
                            outputError(f'List members must all be input pins or all output pins. '
                                        f'The listName: {signalName}, in cell: '
                                        f'{get_column_letter(iColumn + 1)}{iRow + 1}, '
                                        f'contains: {myList.pinIOType.name}s, while '
                                        f'the signalName: {self.pinList[0].signalName}, '
                                        f'in cell: {get_column_letter(iColumn + 1)}{firstRow + 1}, '
                                        f'is an: {self.pinList[0].pinIOType.name}, '
                                        f'This list will not be added to the list.')
                            continue
                    for pin in myList.pinList:
                        self.pinList.append(pin)
                else:
                    outputError(f'Cell: {get_column_letter(iColumn + 1)}{iRow + 1}, defining list: {self.shortName}, '
                                f'has has a name: {signalName}, that is neither a signalName nor a listName. '
                                f'It will be ignored.')
                    continue

        if len(self.pinList) > 0:  # We have a nonzero list length
            self.pinIOType = self.pinList[0].pinIOType
        else:  # it is a zero length list. Save something that is neither INPUT nor OUTPUT
            self.pinIOType = 999
        listDict[self.name] = self  # Save this in the global dictionary

    def setBit(self, bitValue: int, indentLevel: int = 0):
        """
        This is called to set a single or a list of PLC input bit (either physical or a memory/virtual bit)
        If the list is being used in a loop, the single pin corresponding to the loop iteration number is set.
        Otherwise, all bits in the list are set.
        :type bitValue: int: Value we want to force this input to. Should be 0 or 1.
        :type indentLevel: Number of spaces to indent the printed output.
        :return:
        """
        if bitValue:
            bitValue = 1  # Force any True value to 1
        if self.loopIndex >= 0:  # A loop is iterating through this list.
            # Just set the current pin in the list.
            if self.loopIndex < len(self.pinList):
                pin = self.pinList[self.loopIndex]
                pin.setBit(bitValue, indentLevel)
        else:
            # Set every pin in the list
            testPrint(indentLevel, f'Setting list: {self.name}, to: {bitValue}, by doing the following:')
            indentLevel += indentLevelInc
            for pin in self.pinList:
                pin.setBit(bitValue, indentLevel)
