from errorHandler import outputError, testPrint
from globalVariables import variableDict, listDict, pinDict


class Variable:
    """This class handles variables. 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, variableName: str, iRow: int):
        """
        Create the variable object
        :param variableName: String with the name of the variable
        :param iRow: The row number in the worksheet that defines this variable
        """
        if variableName in listDict:
            outputError(f'Row: {iRow + 1}, defines a variable named: {variableName}, '
                        f'with the same name as a list. This is bad practice '
                        f'and may lead to errors.')
        if variableName in pinDict:
            outputError(f'Row: {iRow + 1}, defines a variable named: {variableName}, '
                        f'with the same name as a signal. This is bad practice '
                        f'and may lead to errors.')
        self.name = variableName
        self.presentValue = None  # Set it to not initialized.
        variableDict[variableName] = self

    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 bitValue:
            bitValue = 1  # Force any True value to 1
        self.presentValue = bitValue
        testPrint(indentLevel, f'Variable: {self.name}, set to {bitValue}')

    def checkBit(self, correctValue: int, indentLevel: int = 0):
        """
        This should never be called. It exists since exprClass has a variable that could be a pin or a List or
        a Variable. It should never be called for a variable, but to avoid compiler warnings, this routine exists.
        :type correctValue: 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:
        """
        self.presentValue = correctValue
        outputError(f'Bug---CheckBit in the Variable class has been called and never should be. It was'
                    f'called with arguments: {correctValue} and {indentLevel}')
