from PySide2 import QtWidgets, QtGui, QtCore
import logging

# from global_widgets.global_typeval_popup import TypeValuePopup


class SignallingLineEditWidget(QtWidgets.QLineEdit):
    manualChanged = QtCore.Signal()

    def __init__(self, NativeUI, popup, label):
        super().__init__()
        self.installEventFilter(self)
        self.label_text = label
        self.NativeUI = NativeUI
        self.popUp = popup  # NativeUI.typeValPopupAlpha
        # self.popUp = TypeValuePopup(NativeUI)#,'text edit',0,1,2,3,4)
        # self.popUp.lineEdit.setValidator(None)  # nsure it accepts text
        # self.popUp.okButton.clicked.connect(self.okButtonPressed)
        # self.popUp.cancelButton.clicked.connect(self.cancelButtonPressed)

    def okButtonPressed(self):
        val = self.popUp.lineEdit.text()
        self.setText(val)
        self.popUp.close()
        self.manualChanged.emit()

    def cancelButtonPressed(self):
        self.popUp.lineEdit.setText(self.popUp.lineEditp.saveVal)
        self.popUp.close()

    def eventFilter(self, source, event):
        if source is self and event.type() == QtCore.QEvent.MouseButtonPress:
            self.popUp.populatePopup(self, self.NativeUI.display_stack.currentWidget())
            self.NativeUI.display_stack.setCurrentWidget(self.popUp)
            return True
        return False

    def value(self):
        return self.text()

    def setValue(self, value):
        self.setText(str(value))


class LabelledLineEditWidget(QtWidgets.QWidget):
    def __init__(self, NativeUI, popup, infoArray, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # logging.debug(infoArray)
        self.NativeUI = NativeUI
        self.cmd_type, self.cmd_code = "", ""
        self.min, self.max, self.step = 0, 10000, 0.3
        self.decPlaces = 2
        if len(infoArray) == 9:
            self.label, self.units, self.tag, self.cmd_type, self.cmd_code, self.min, self.max, self.step, self.decPlaces = (
                infoArray
            )
        elif len(infoArray) == 6:
            self.label, self.units, self.tag, self.cmd_type, self.cmd_code, self.initText = (
                infoArray
            )
        elif len(infoArray) == 3:
            self.label, self.units, self.tag = infoArray
        self.manuallyUpdated = False
        self.layout = QtWidgets.QHBoxLayout()
        self.widgetList = []

        # if self.label != "":
        self.nameLabel = QtWidgets.QLabel()
        self.nameLabel.setFont(NativeUI.text_font)
        self.nameLabel.setStyleSheet(
            "color:" + NativeUI.colors["page_foreground"].name() + ";"
        )
        self.widgetList.append(self.nameLabel)

        self.signalling_spin = SignallingLineEditWidget(NativeUI, popup, self.label)
        self.signalling_spin.setText(self.initText)
        self.signalling_spin.setStyleSheet(
            "QLineEdit{"
            "    border: none;"
            "    color:" + NativeUI.colors["page_foreground"].name() + ";"
            "}"
            "QLineEdit[bgColour='1']{"
            "    background-color:" + NativeUI.colors["page_foreground"].name() + ";"
            "}"
            "QLineEdit[bgColour='0']{"
            "    background-color:"
            + NativeUI.colors["button_background_disabled"].name()
            + ";"
            "}"
            "QLineEdit[textColour='1']{"
            "    color:" + NativeUI.colors["page_background"].name() + ";"
            "}"
            "QLineEdit[textColour='0']{"
            "    color:" + NativeUI.colors["page_foreground"].name() + ";"
            "}"
            "QLineEdit[textColour='2']{"
            "    color:" + NativeUI.colors["red"].name() + ";"
            "}"
        )

        self.signalling_spin.setFont(NativeUI.text_font)
        self.signalling_spin.setProperty("textColour", "1")
        self.signalling_spin.setProperty("bgColour", "1")

        self.signalling_spin.textChanged.connect(self.textUpdate)
        if self.cmd_type == "":
            self.signalling_spin.setReadOnly(True)
            self.signalling_spin.setProperty("bgColour", "1")
        self.widgetList.append(self.signalling_spin)

        # if self.units != "":
        self.unitLabel = QtWidgets.QLabel()
        self.unitLabel.setFont(NativeUI.text_font)
        self.unitLabel.setStyleSheet(
            "color:" + NativeUI.colors["page_foreground"].name() + ""
        )
        self.widgetList.append(self.unitLabel)

        for widget in self.widgetList:
            self.layout.addWidget(widget)

        self.setLayout(self.layout)
        self.localise_text(NativeUI.text)

    def textUpdate(self):
        self.manuallyUpdated = True
        self.signalling_spin.setProperty("textColour", "2")
        self.signalling_spin.style().polish(self.signalling_spin)

    def update_value(self, db):
        newVal = db[self.tag]
        if newVal == {}:
            a = 1  # do nothing
        else:
            logging.debug("got a personal db")
            self.signalling_spin.setText(newVal)
            self.signalling_spin.setProperty("textColour", "1")
            self.signalling_spin.style().polish(self.signalling_spin)

    def get_value(self):
        return self.signalling_spin.text()

    def set_size(self, x: int, y: int, spacing: int = 5) -> int:
        """
        Set the size of the widget.
        Also rescale the elements within it to equally distribute the width
        """
        logging.debug("line_edit", self.label)

        if x is not None:
            self.setFixedWidth(x)
            x_widget = int(0.9 * x / 8)
            self.nameLabel.setFixedWidth(3 * x_widget)
            self.signalling_spin.setFixedWidth(4 * x_widget)
            self.unitLabel.setFixedWidth(1 * x_widget)
        if y is not None:
            self.setFixedHeight(y)
            for widget in self.widgetList:
                widget.setFixedHeight(y)

        self.nameLabel.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.signalling_spin.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.unitLabel.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.layout.setSpacing(0)
        # self.layout.setSpacing(spacing)
        return 0

    def localise_text(self, text: dict) -> int:
        """
        Source the text for the labels from the specified dictionary.
        """
        if self.label == "":
            self.nameLabel.setText("")
        else:
            self.nameLabel.setText(text[self.tag])

        if self.units == "":
            self.unitLabel.setText("")
        else:
            self.unitLabel.setText(text[self.units])

        return 0
