import logging
from typing import Optional

from PySide6 import QtCore, QtWidgets

from hyperborea.dark_mode import set_style
from hyperborea.preferences import (read_bool_setting, write_bool_setting)

from .ui.ui_preferences import Ui_PreferencesDialog

logger = logging.getLogger(__name__)


original_palette = None


class PreferencesDialog(Ui_PreferencesDialog, QtWidgets.QDialog):
    def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
        super().__init__(parent)

        self.settings = QtCore.QSettings()

        self.setupUi(self)

        # this is easily forgotten in Qt Designer
        self.tabWidget.setCurrentIndex(0)

        self.accepted.connect(self.write_settings)
        self.darkMode.toggled.connect(self.dark_mode_updated)
        self.lightMode.toggled.connect(self.dark_mode_updated)

        self.read_settings()

    @QtCore.Slot()
    def dark_mode_updated(self) -> None:
        dark_mode = self.darkMode.isChecked()
        set_style(QtWidgets.QApplication.instance(), dark_mode)  # type: ignore

    def read_settings(self):
        self.unitPreferences.read_settings()

        dark_mode = read_bool_setting(self.settings, "DarkMode", True)
        if dark_mode:
            self.darkMode.setChecked(True)
        else:
            self.lightMode.setChecked(True)

    @QtCore.Slot()
    def write_settings(self) -> None:
        self.unitPreferences.write_settings()

        dark_mode = self.darkMode.isChecked()
        write_bool_setting(self.settings, "DarkMode", dark_mode)
