
import openpyxl

import globalVariables
from errorHandler import testPrint, outputError
from globalVariables import pinDict, parts
from pinClass import PinPLCMemory, PinPLC

_accessControlPLCExists = False  # Set to true if the test setup has an access control (AC) PLC.
pendingGroupLatchReset = False  # Set to true when there is a group latch reset pending.


def setAllExternalInputs(value: int, indentLevel: int = 0):
    """
    This routine zeros all the external inputs to the PLC under test
    :param value: Value (0 or 1) to set all the inputs to.
    :param indentLevel: Number of spaces to indent stuff which gets printed
    :return:
    """
    testPrint(indentLevel, f'____Setting all inputs to {value}')
    for part in parts:
        if isinstance(part, Part):  # this is a part (as opposed to a routine
            if part.input:  # This part contains input pins
                part.setAllInputs(value)


class Part:
    """This is the base class that defines a part. A part can be a logic diagram, the In or OUt port
    of a PLC or a block of bits used to communicate between PLCs or between a PLC and EPICS"""

    def __init__(self):
        # initialize a list of pins that this part will have
        self.pins = {}  # This is a dictionary of all the pins used in this part.
        # each dictionary entry is of the form <pin function>: pin object.
        self.partName = 'dummy'  # this will be filled in by method initFromExcel
        self.input = False  # will be overridden by the subclass

    def setAllInputs(self, value: int):
        """
        This sets all pins of the part to value. Normally only used for IO parts.
        :param value: Should be 0 or 1.
        :return:
        """
        indentLevel = -1  # suppress printing of each bit being set.
        for pin in self.pins.values():
            pin.setBit(value, indentLevel)


class PartIO(Part):

    def __init__(self, boolInput):
        super().__init__()
        self.columnNames = ['signalName', 'slot', 'pinNumber', 'PVchan', 'englishDescription']
        # Above may be overridden by child classes with the column names expected in the spreadsheet.
        # sheets safety_in and  safety_out, AC_in and AC_out do not override this.
        self.fullyDefinesLocation = [1, 2]
        # Above will be overridden by child classes giving the column numbers that fully specify the location
        # of the I/O bit.
        self.input = boolInput  # true if this contains PLC input pins. false for output pins
        self.subZone = ''  # name of subZone this PLC is used for. e.g. LI01-3 or LI06-7
        self.offset = 0  # offset in the AC PLC buffer where the data for this safety PLC starts. 0 means there
        # is no AC PLC and the safety PLC is directly read/written by EPICS.

    def initFromExcel(self, s: openpyxl.workbook.workbook.Worksheet):
        """This initializes an IO part (e.g. The input pins on a PLC or the memory bits in a PLC to PLC
        communications link) by reading the worksheet which is passed in as parameter s.
        Each line of that worksheet contains data for an I/O pin. The expected column names are in
        self.columnNames. Depending on the type Of I/O, different data is available for each pin so a different
        pin class is used."""

        isIOList = 'pinNumber' in self.columnNames  # true if this sheet contains PLC I/O list. Otherwise it is a
        # memory bit map.

        self.partName = s.title  # name the part the same as the name of the sheet we initialize it from.
        iRow = 1  # The Excel row we are working on.
        headingError = False

        # Cells B1 and C1 may contain strings of the form "subZone=<name>" and "offset=<n>". Decode and save them
        for cell in ['B1', 'C1']:
            value = s[cell].value
            if value is not None:
                if value[0:8] == 'subZone=':
                    self.subZone = value[8:]
                elif value[0:7] == 'offset=':
                    myString = value[7:]
                    if myString.isdigit():
                        self.offset = int(myString)
                    else:
                        outputError(f'Cell: {cell}, with content: "{value}", gives a non-integer offset. '
                                    f'It will be ignored')
                else:
                    outputError(f'Cell: {cell}, with content: "{value}", has an invalid value. '
                                f'It should start with "offset=" or "subZone=".  It will be ignored.')
        # end loop over cells

        # The first row should contain a string of the form 'partType=safety_in. We will skip it.
        isInput = '_in' in s['A1'].value
        # The second row should contain column headings appropriate for this partType.

        # loop over rows of the worksheet, skipping first row
        for r in s.iter_rows(2):
            iRow += 1
            if iRow == 2:
                # this is the second row of the spread sheet. Make sure it has the correct column headings
                if len(r) < len(self.columnNames):  # Not enough columns in spreadsheet
                    outputError(f'Not enough columns in the worksheet. Expected: {len(self.columnNames)}, '
                                f'found: {len(r)}. Sheet will be ignored.')
                    break
                # loop over columns
                for iColumn, columnName in enumerate(self.columnNames):
                    if columnName != r[iColumn].value:
                        outputError(f'Heading in column: {iColumn + 1} should be: {columnName},'
                                    f' and is: {r[iColumn].value}')
                        headingError = True
                continue
            if headingError:
                break  # column headings are wrong, so skip reading the rest of the worksheet.

            # We are now in the third or later row of the sheet, so it contains information about a pin or memory bit
            # make sure this new pin does not have name that has been used before.
            signalName = r[0].value
            if signalName is None:
                continue  # signalName is blank, so skip this line.
            if signalName in self.pins:
                outputError(f'The signal name: {signalName}, appears twice on worksheet {s.title}, in '
                            f'rows: {iRow} and {self.pins[signalName].excelRow}')
            elif signalName in pinDict:
                outputError(f'The signal name: {signalName} on row {iRow}, appeared on a previous worksheet '
                            f'named: {pinDict[signalName].parent.partName} on '
                            f'row: {pinDict[signalName].excelRow}.')

            if 'spare' in signalName.lower():  # This is a spare bit, so ignore it
                continue

            # Check to see if this signal uses the same pin/slot/bit as a previously entered signal
            for pin in self.pins.values():  # loop over pins on this part
                duplicate = True
                for column in self.fullyDefinesLocation:
                    columnName = self.columnNames[column]
                    if columnName == 'bitNumber':
                        # the pin Object names the property 'pinNumber' even when column heading is 'bitNumber'
                        columnName = 'pinNumber'
                    if r[column].value != getattr(pin, columnName):
                        duplicate = False
                        break
                # end loop over columns

                if duplicate:
                    outputError(f'Part: {self.partName}, has an I/O bit or pin used twice. '
                                f'The two signal names are: {signalName} on row: {iRow}, '
                                f'and: {pin.signalName}, on row: {pin.excelRow}.')
                    break

            # If there is a column titled PVchan, check that this new PVchan is different than all previous ones
            try:
                column = self.columnNames.index('PVchan')
                # if we make it here, there is a column titled "PVchan"
                for pin in self.pins.values():  # loop over pins on this part
                    if pin.PVchan == r[column].value:
                        outputError(f'Part: {self.partName}, has a PVchan used twice. '
                                    f'The two signal names are: {signalName} or row: {iRow}, '
                                    f'and: {pin.signalName}, on row: {pin.excelRow}.')
            except ValueError:
                pass  # There is no column named PVchan which is OK. Just don't do the check

            """ later, use a dynamic way to choose which pin class to use instead of if statement. example below:
            module = __import__(module_name)
            class_ = getattr(module, class_name)
            instance = class_()"""

            # Create a pin with the data in the row.
            if isIOList:
                self.pins[signalName] = PinPLC(self, signalName, isInput, r[1].value, r[2].value,
                                               str(r[3].value), r[4].value)
                PVname = 'BKHF:B34:****'.replace('****', self.pins[signalName].PVchan)
                PVsevr = PVname[0:-4] + ':Error.SEVR'  # the Beckhoff driver gives only gives a severity
                # for the whole system, not per channel
                self.pins[signalName].PVname = PVname
                self.pins[signalName].PVsevr = PVsevr
            else:
                # it is a list of memory bits
                self.pins[signalName] = PinPLCMemory(self, signalName, self.input, str(r[1].value),
                                                     r[2].value)
                # add extra attributes corresponding to the extra columns.
                for iColumn, columnName in enumerate(self.columnNames[2:]):
                    setattr(self.pins[signalName], columnName, r[iColumn + 2].value)
                bitNumber = self.pins[signalName].pinNumber
                if bitNumber[0] == '+':  # Sometimes a "+" precedes the byte number
                    bitNumber = bitNumber[1:]  # get rid of it.

                # We are either directly reading AC info from an AC PLC, or directly reading safety PLC info
                # from a safety PLC or reading safety PLC info from a buffer in the AC PLC.
                # The PVname to be used and the meaning of bitNumber depends on which of the 3 cases we are doing.
                allOK = False
                if self.input:
                    inOut = 'OUT'
                else:
                    inOut = 'IN'
                PVname = ''
                if isinstance(self, PartEpicsToAC) or isinstance(self, PartACtoEpics):
                    # We are directly reading or writing  AC info from the AC PLC.
                    # the bitNumber should be of the form xx.y where xx is a byte number and y is the bit
                    # within the byte. If y is zero, since Excel considers he cell contents to be a number and not
                    # a string, the ".0" gets dropped. I have to manually add it back in.
                    byte_bit = bitNumber.split('.')
                    if len(byte_bit) == 1:  # probably a ".0" got dropped
                        byte_bit.append('0')
                    if len(byte_bit) == 2:  # There was a single "." as there should be
                        if byte_bit[0].isdigit() and byte_bit[1].isdigit():  # this is as expected.
                            byteNumber = int(byte_bit[0])
                            bitN = int(byte_bit[1])
                            if byteNumber >= 0 and 0 <= bitN < 8:
                                PVname = f'PPS:B34:PP03:{inOut}{byteNumber:03d}:{bitN}'
                                allOK = True
                    if not allOK:
                        outputError(f'Signal name: {signalName}, has an invalid bitNumber: {bitNumber}. '
                                    f'It must be of the form xxx.y where and y are integers and y < 8. '
                                    f'The signal will be ignored.')
                        continue
                elif self.offset == 0:  # The bit is accessed directly from the safety PLC
                    PVname = 'PLC:B34:PP02:****:A0'.replace('****', bitNumber)
                    if self.input:
                        PVname += 'i'
                    else:
                        PVname += 'o'
                else:  # The bit is transferred to the Access Control PLC and EPICS accesses it from there
                    # at the given byte offset.
                    if bitNumber.isdigit():
                        bitNumber = int(bitNumber)
                        byteNumber = self.offset + bitNumber // 8
                        bitN = bitNumber % 8
                        # PVname for AC PLC is of the form PPS:B34:PP03:IN050:2 (for byte 50 bit 2)
                        PVname = f'PPS:B34:PP03:{inOut}{byteNumber:03d}:{bitN}'
                        globalVariables.calcTimePLC = globalVariables.passThroughTime  # Delay time from last
                        # caput before a caget must
                        # be increased to allow time for the data to propagate through the Ac PLC.
                    else:
                        outputError(f'Signal name: {signalName}, has an invalid bitNumber: {bitNumber}. '
                                    f'It must be an integer between 0 and 127. '
                                    f'The signal will be ignored.')
                        continue
                self.pins[signalName].PVname = PVname
                self.pins[signalName].PVsevr = PVname + '.SEVR'

            self.pins[signalName].excelRow = iRow
            pinDict[signalName] = self.pins[signalName]  # Save the pin to the global dictionary

            # end loop over rows


class PartMemory(PartIO):
    # This class handles the memory bits in a PLC
    def __init__(self, boolInput):
        super().__init__(boolInput)


class PartEpicsToAC(PartMemory):
    # This class handles the memory bits going from EPICS to the Access Control PLC
    def __init__(self):
        super().__init__(True)
        self.columnNames = ['signalName', 'bitNumber', 'englishDescription']


class PartACtoEpics(PartMemory):
    # This class handles the memory bits going from EPICS to the Access Control PLC
    def __init__(self):
        super().__init__(False)
        self.columnNames = ['signalName', 'bitNumber', 'englishDescription']


class PartACtoSafety(PartMemory):
    # This class handles the memory bits going from EPICS to the Access Control PLC
    def __init__(self):
        super().__init__(True)
        self.columnNames = ['signalName', 'bitNumber', 'englishDescription']


class PartSafetyToAC(PartMemory):
    # This class handles the memory bits going from EPICS to the Access Control PLC
    def __init__(self):
        super().__init__(False)
        self.columnNames = ['signalName', 'bitNumber', 'englishDescription']
