#!/usr/bin/env python3

"""
spin_buttons_widget.py
"""

__author__ = ["Benjamin Mummery", "Tiago Sarmento"]
__credits__ = ["Benjamin Mummery", "Dónal Murray", "Tim Powell", "Tiago Sarmento"]
__license__ = "GPL"
__version__ = "0.0.1"
__maintainer__ = "Tiago Sarmento"
__email__ = "tiago.sarmento@stfc.ac.uk"
__status__ = "Development"

# from customPopup2 import customPopup2
import sys

from PySide2 import QtCore, QtGui, QtWidgets

# from global_widgets.global_typeval_popup import TypeValuePopup

# from global_widgets.global_ok_cancel_buttons import okButton, cancelButton
from widget_library.ok_cancel_buttons_widget import OkButtonWidget, CancelButtonWidget
from global_widgets.global_spinbox import signallingSpinBox

# from global_widgets.global_send_popup import SetConfirmPopup


class SpinButton(QtWidgets.QFrame):
    """TO DO: Implement command sending"""

    def __init__(self, NativeUI, popup, infoArray):
        super().__init__()

        self.manuallyUpdated = False
        # self.setStyleSheet("background-color:blue;")
        self.currentVal = 0
        if len(infoArray) == 10:
            self.label_text, self.units, self.tag, self.cmd_type, self.cmd_code, self.min, self.max, self.initVal, self.step, self.decPlaces = (
                infoArray
            )
        # logging.debug('before')
        # logging.debug(self.cmd_type)
        self.cmd_type = self.cmd_type.replace("SET_TARGET_", "SET_TARGET_CURRENT")
        # self.cmd_type = settings[3]
        # self.cmd_code = settings[4]
        # self.tag = settings[2]
        self.NativeUI = NativeUI

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # create and style label
        self.label = QtWidgets.QLabel()
        self.label.setText(NativeUI.text[self.label_text])
        self.label.setFont(self.NativeUI.text_font)

        labelBgColour = "rgb(60,58,60)"
        self.label.setStyleSheet(
            "color:" + NativeUI.colors["button_foreground_enabled"].name() + ";"
            "background-color:"
            + NativeUI.colors["button_background_enabled"].name()
            + ";"
        )
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.layout.addWidget(self.label)

        self.signalling_spin = signallingSpinBox(
            NativeUI,
            popup,
            self.label_text,
            self.min,
            self.max,
            self.initVal,
            self.step,
            self.decPlaces,
        )
        # self.signalling_spin.lineEdit().setStyleSheet("border:blue;")

        boxStyleString = (
            "QDoubleSpinBox{"
            "   border:none;"
            "   background-color: black;"
            "}"
            "QDoubleSpinBox[colour='0'] {"
            "   color:green;"
            "}"
            "QDoubleSpinBox[colour='1'] {"
            "   color:" + NativeUI.colors["highlight"].name() + ";"
            "}"
            "QDoubleSpinBox[colour='2'] {"
            "    color:red;"
            "}"
        )
        upButtonStyleString = "QDoubleSpinBox::up-button{" "height:50;" "width:50;" "}"

        downButtonStyleString = upButtonStyleString.replace("up", "down")
        upButtonStyleString = "QDoubleSpinBox::up-button{" "height:30;" "width:40;" "}"
        downButtonStyleString = upButtonStyleString.replace("up", "down")
        self.signalling_spin.setStyleSheet(
            boxStyleString + upButtonStyleString + downButtonStyleString
        )
        self.signalling_spin.setProperty("colour", "1")
        self.signalling_spin.setButtonSymbols(
            QtWidgets.QAbstractSpinBox.ButtonSymbols.PlusMinus
        )
        self.signalling_spin.setAlignment(QtCore.Qt.AlignCenter)
        self.signalling_spin.manualChanged.connect(self.manualChanged)
        self.signalling_spin.programmaticallyChanged.connect(self.manualChanged)
        self.signalling_spin.setSizePolicy(
            QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed
        )
        self.signalling_spin.setFont(self.NativeUI.value_font)
        self.layout.addWidget(self.signalling_spin)
        self.setLayout(self.layout)
        self.setFixedWidth(300)
        # self.setStyleSheet("border:2px solid white; border-radius:4px; padding:0px;")

    def update_value(self, db):
        newVal = db
        if (newVal == {}) or (self.cmd_code == ""):
            a = 1  # do nothing
        else:
            if not self.manuallyUpdated:
                self.signalling_spin.setValue(newVal[self.tag])
                self.setTextColour(1)
            else:
                if round(self.signalling_spin.value(), self.decPlaces) == round(
                    newVal[self.tag], self.decPlaces
                ):
                    self.manuallyUpdated = False
                    self.setTextColour(1)

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

    def set_value(self, value):
        self.signalling_spin.setValue(value)
        self.manuallyUpdated = True
        self.signalling_spin.programmaticallyChanged.emit()

    def manualChanged(self):
        """Called when user manually makes a change. Stops value from updating and changes colour"""
        self.manuallyUpdated = True
        self.setTextColour(2)
        return 0

    def setTextColour(self, option):
        """Set text colour and unpolish polish widget to show change"""
        self.signalling_spin.setProperty("colour", option)
        self.signalling_spin.style().unpolish(self.signalling_spin)
        self.signalling_spin.style().polish(self.signalling_spin)
        return 0

    def set_label_font(self, font) -> int:
        """
        Set the font for the spinbox label.
        """
        self.label.setFont(font)
        return 0

    def set_value_font(self, font) -> int:
        """
        Set the font for the spinbox value display.
        """
        self.signalling_spin.setFont(font)
        return 0

    def localise_text(self, text: dict) -> int:
        """
        Update the label text to the specified dictionary.
        """
        self.label.setText(text[self.label_text])
        return 0
