from global_widgets.global_spinbox import labelledSpin
from widget_library.startup_calibration_widget import calibrationWidget
from widget_library.ok_cancel_buttons_widget import (
    OkButtonWidget,
    CancelButtonWidget,
    OkSendButtonWidget,
)
from global_widgets.global_send_popup import SetConfirmPopup
from PySide2.QtWidgets import QRadioButton
from datetime import datetime
import json
from PySide2 import QtWidgets, QtGui, QtCore
import logging


class MaintenanceHandler(
    QtWidgets.QWidget
):  # chose QWidget over QDialog family because easier to modify

    OpenPopup = QtCore.Signal(list)
    MaintenanceConfigUpdate = QtCore.Signal(dict)

    def __init__(self, NativeUI, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.NativeUI = NativeUI
        self.calibDict = {}
        self.calibs_done_dict = {}
        self.activeWidget = None

    def add_widget(self, widget, key: str):
        if isinstance(widget, labelledSpin):
            self.spinDict[key] = widget
            widget.cmd_type = widget.cmd_type.replace("startup", "CURRENT")
        if isinstance(widget, calibrationWidget):
            self.calibDict[key] = widget
        if (
            isinstance(widget, OkButtonWidget)
            or isinstance(widget, CancelButtonWidget)
            or isinstance(widget, OkSendButtonWidget)
        ):
            self.buttonDict[key] = widget
        if isinstance(widget, QRadioButton):
            if widget.text() in self.NativeUI.modeList:
                self.modeRadioDict[key] = widget
            else:
                self.settingsRadioDict[key] = widget

    def handle_calibrationPress(self, calibrationWidget) -> int:
        """
        When a calibration buttonis pressed, run the corresponding calibration. If all
        calibrations are completed, emit the CalibrationComplete signal.

        Currently doesn't actually do any calibrations, just a placeholder for now.
        """
        self.activeWidget = calibrationWidget
        logging.debug(self.activeWidget)
        logging.debug(NativeUI.messagePopup)
        self.NativeUI.messagePopup.setLabelText(calibrationWidget.infoDict["message"])

    def carryout_calibration(self) -> int:
        assert self.activeWidget is not None
        calibrationWidget = self.activeWidget
        if "calibration" in calibrationWidget.infoDict["label"]:
            self.NativeUI.q_send_cmd("DO_CALIBRATION", "DO_CALIBRATION")
        elif "Leak_Test" in calibrationWidget.infoDict["label"]:
            self.NativeUI.q_send_cmd()
        else:
            logging.debug("ERROR: label does not mach any calibration procedure")

        # self.NativeUI.display_stack.setCurrentWidget(self.NativeUI.startupWidget)
        calibrationWidget.progBar.setValue(100)
        calibrationWidget.lineEdit.setText("completed")

        with open("NativeUI/configs/maintenance_config.json", "r") as json_file:
            startupDict = json.load(json_file)
            startupDict[calibrationWidget.key]["last_performed"] = int(
                datetime.now().timestamp()
            )
        with open("NativeUI/configs/maintenance_config.json", "w") as json_file:
            json.dump(startupDict, json_file)
            self.MaintenanceConfigUpdate.emit(startupDict)
            logging.debug("Writing to %s", json_file)
        self.calibs_done_dict[calibrationWidget.key] = True

        return 0

    def localise_text(self, text: dict) -> int:
        """
        Change the language of text elements.
        """
        pass
