from __future__ import annotations

import time
from enum import Enum, auto
from typing import TYPE_CHECKING

from epics import caput, caget

import globalVariables
from errorHandler import testPrint, outputError
# from globalVariables import maxSamples

if TYPE_CHECKING:  # This is done to avoid a circular import error
    from partClass import Part


class PinIOType(Enum):
    """This defines an enum used in the Pin class"""
    INPUT = auto()  # acts as the input to a part
    OUTPUT = auto()  # serves as an output from the part
    BUFFER = auto()  # Used for memory bits for inter PLC communication. These memory bits are essentially buffers
    # and hence have both inputs and outputs.


class Pin:
    """ This is the base class that defines a pin for a part."""

    def __init__(self, parent, function, pinIOType: PinIOType):
        """
        Create a pin object which describes a pin on a logic part or a bit in an I/O part.
        :param parent: The part object that created this pin
        :param function: a string that describes the purpose/name of the input
        :param pinIOType: An enum PinIOType with value INPUT, OUTPUT or BUFFER
        """
        self.function = function
        self.signalName = function
        self.name = function
        self.pinIOType = pinIOType  # The kind of I/O this pin does. eg. input or output or buffer
        self.parent: Part = parent  # the Part object that owns this pin
        self.presentValue = 2  # The present logic value on this pin. 0 is false, 1 is true, 2 is uninitialized
        self.PVname = None
        self.PVsevr = None
        self.description = None  # Will contain a description of the bit.
        self.excelRow = None  # Will contain the row number in Excel that defined this pin.
        self.used = False  # Will be set to true when some test uses this pin.
        self.pauseCommanded = False  # Will be set to true when a check command says to pause for EPICS display check
        self.pauseComment = ''  # Will be set to the comment on the check command line that requested a pause

    def setBit(self, bitValue: int, indentLevel: int = 0):
        """
        This is called to set a PLC input bit (either physical or a memory/virtual bit)
        :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 globalVariables.abortTest:  # User has requested the run be aborted
            raise SystemExit

        if bitValue:
            bitValue = 1  # Force any True value to 1
        if self.presentValue == bitValue:
            testPrint(indentLevel, f'____Set input: {self.function}, to '
                                   f'{bitValue} on part: {self.parent.partName}, but skip '
                                   f'as was {bitValue}.')
        else:
            self.presentValue = bitValue
            if self.presentValue == bitValue:
                testPrint(indentLevel, f'____Set input: {self.function}, to '
                                       f'{bitValue} on part: {self.parent.partName}')
                globalVariables.totalSets += 1
                if globalVariables.haveRealHardware:
                    myTime = int(time.time() * 1000)  # Time in ms
                    globalVariables.timeOfLastCaput = myTime
                    globalVariables.timeOfLastWaitOrCaput = myTime
                    # debugPrint(f'{myTime} is time we caput PVname: {self.PVname}')
                    value = caput(self.PVname, bitValue, timeout=2)  # This actually sets the bit in the Beckhoff
                    sevr = caget(self.PVsevr, timeout=2, as_string=True)  # see if the operation worked
                    if value is None:  # operation failed, probably timed out.
                        outputError('caput timed out. Is soft IOC running? Does this PV exist?')
                    elif sevr == 'INVALID':
                        outputError(f'caput returned a bad SEVR: {sevr}. Does PLC have power and network connection?')


class PinPLC(Pin):
    """Ths adds info to the Pin class for the Input and Output pins of a PLC"""

    def __init__(self, parent, function, boolInput, slot, pinNumber, PVchan, description):
        """
        :param parent: The part object that created this pin
        :param function: a string describing the function/name of the pin
        :param boolInput: a bool that is true if this is an input pin, false if an output pin
        :param slot: the slot the IO module of the PLC is in
        :param pinNumber: the IO pinNumber of the connection on the PLC
        :param PVchan: the PV channel of the Beckhoff bit which is connected to this pin
        :param description: A string describing what this pin does. e.g. "The micro-switch on the sector 26 door"
        """
        if boolInput:
            pinIOType = PinIOType.INPUT
        else:
            pinIOType = PinIOType.OUTPUT

        super().__init__(parent, function, pinIOType)
        # pinIOType is inverted in the above line because an external input to the PLC actually serves as an output
        # to the logic within a PLC. If that isn't obvious, then consider that when wiring up a circuit with a net,
        # it is OK to connect a single output to multiple inputs, but not vice versa. It would NOT be OK to different
        # PLC inputs to an input in the internal PLC logic. Hence a physical external PLC input is an output to the
        # logic inside a PLC. Another way to see this is to think of the physical PLC input as a buffer. A wire
        # is connected to the physical input and the OUTPUT of the buffer goes to the internal logic.
        self.slot = slot
        self.pinNumber = pinNumber
        # PVchan should be string in the form DMMPP where:
        # D is a letter indicating the Din rail the PLC is on
        # MM is an integer indicating which slot of the PLC the signal comes from (counting from 1 for the base
        # unit of the PILZ and 1 for the first I/O module of a Siemens)
        # PP is an integer Pin number of the PLC signal. These count from 1 on the Beckhoff and 0 on the Pilz
        # Here we check to make sure that the input has this format.
        if len(PVchan) == 5 and PVchan[-4:].isdigit() and \
                (PVchan[-5] == 'A' or PVchan[-5] == 'B' or PVchan[-5] == 'C'):
            self.PVchan = PVchan
        else:
            self.PVchan = 'Z9999'  # set to something legal, but ridiculous.
            outputError(f'Part: {parent.partName}, pin: {self.signalName}, has an invalid PVchan: {PVchan}.'
                        f'It should be of the form DMMPP where: '
                        f'D is a letter (A, B or C) indicating the Din rail the PLC is on; '
                        f'MM is an integer indicating which slot of the PLC the signal comes from '
                        f'PP is an integer Pin number of the PLC signal.')

        self.PVname = None  # will be filled in later
        self.PVsevr = None  # will be filled in later
        self.description = description


class PinPLCMemory(Pin):
    """This adds info to the pin class for the memory of a PLC that is used to communicate with another PLC or EPICS"""

    def __init__(self, parent, function, boolInput, bitNumber, description):
        """
        :param parent: The part object that created this pin
        :param function: a short string describing the function/name of the memory bit
        :param boolInput: a bool that is true if this is an input pin, false if an output pin
        :param bitNumber: the bit number in the PLC memory
        """
        if boolInput:
            pinIOType = PinIOType.INPUT
        else:
            pinIOType = PinIOType.OUTPUT
        # Following commented out line is for old code that used logic blocks.
        # super().__init__(parent, function, PinIOType.BUFFER)
        super().__init__(parent, function, pinIOType)
        self.pinNumber = bitNumber
        self.PVname = f'bitNumber{bitNumber}'
        self.PVsevr = self.PVsevr
        self.description = description
