from global_widgets.global_spinbox import labelledSpin
from widget_library.ok_cancel_buttons_widget import (
    OkButtonWidget,
    CancelButtonWidget,
    OkSendButtonWidget,
)

# from global_widgets.global_send_popup import SetConfirmPopup
from widget_library.line_edit_widget import LabelledLineEditWidget
from handler_library.handler import PayloadHandler
from PySide2.QtCore import Signal
from PySide2 import QtWidgets, QtGui, QtCore
import logging


class PersonalHandler(
    PayloadHandler
):  # chose QWidget over QDialog family because easier to modify

    UpdatePersonal = Signal(dict)
    OpenPopup = QtCore.Signal(PayloadHandler, list)

    def __init__(self, NativeUI, *args, name="Personal handler", **kwargs):
        super().__init__(["PERSONAL"], *args, name=name, **kwargs)
        self.NativeUI = NativeUI
        self.spinDict = {}
        self.buttonDict = {}
        self.textDict = {}
        self.__outdict = {
            "name": "placeholder_name",
            "patient_id": "placeholder_id",
            "age": 0.0,
            "sex": "placeholder_sex",
            "height": 0.0,
            "weight": 0.0,
        }

    def add_widget(self, widget, key: str):
        if isinstance(widget, labelledSpin):
            self.spinDict[key] = widget
        if isinstance(widget, LabelledLineEditWidget):
            self.textDict[key] = widget
        if (
            isinstance(widget, OkButtonWidget)
            or isinstance(widget, CancelButtonWidget)
            or isinstance(widget, OkSendButtonWidget)
        ):
            self.buttonDict[key] = widget

    def active_payload(self, *args, **kwargs) -> int:
        """
        When the personal data is updated, extract those parameters needed for display
        and store them in self.__outdict.
        """
        current_data = self.get_db()
        for key in self.__outdict.keys:
            self.__outdict[key] = current_data[key]
        return 0

    def on_timeout(self) -> int:
        self.UpdatePersonal.emit(self.__outdict)
        return 0

    def handle_okbutton_click(self, key):
        message, command = [], []
        for key, widget in dict(self.spinDict, **self.textDict).items():
            if widget.manuallyUpdated:
                setVal = widget.get_value()
                if isinstance(setVal, float) or isinstance(setVal, int):
                    setVal = round(setVal, widget.decPlaces)
                message.append("set" + key + " to " + str(setVal))
                command.append([widget.cmd_type, widget.cmd_code, setVal])
        logging.info(command)
        self.commandList = command
        if "send" in key:
            self.sendCommands()
        else:
            logging.debug("open popup please")
            self.OpenPopup.emit(self, message)

    def sendCommands(self):
        if self.commandList == []:
            a = 1
        else:
            for command in self.commandList:
                self.NativeUI.q_send_cmd(*command)
            self.commandSent()
        return 0

    def commandSent(self):
        self.commandList = []
        for widget in dict(self.spinDict, **self.textDict).values():
            widget.manuallyUpdated = False
        self.refresh_button_colour()

    def handle_manual_change(self, changed_spin_key):
        self.refresh_button_colour()

    def refresh_button_colour(self):
        self.manuallyUpdated = False
        for key, widget in dict(self.spinDict, **self.textDict).items():
            self.manuallyUpdated = self.manuallyUpdated or widget.manuallyUpdated
        for button in self.buttonDict:
            self.buttonDict[button].setColour(str(int(self.manuallyUpdated)))
