from typing import TYPE_CHECKING

import PySide2.QtCore as QtC
import PySide2.QtGui
import PySide2.QtGui as QtG
import PySide2.QtWidgets as QtW
from .model import ListModel
from .style_catalog_settings import StyleCatalogSettings
from .ui.style_catalog_main_ui import Ui_Dialog

if TYPE_CHECKING:
    from .__init__ import StyleCatalogs


class StyleCatalogMain(QtW.QDialog, Ui_Dialog):

    def __init__(self, plugin: 'StyleCatalogs', parent=None) -> None:
        QtW.QDialog.__init__(self, parent)
        self.init_ui_common()

        self.plugin = plugin
        self.settings_manager = plugin.settings_manager
        self.model = ListModel(self.plugin)
        self.ui_ok: QtW.QPushButton = self.buttonBox.button(QtW.QDialogButtonBox.Ok)
        self.ui_cancel: QtW.QPushButton = self.buttonBox.button(QtW.QDialogButtonBox.Cancel)

        self.init_ui()

    def init_ui_common(self) -> None:
        self.setupUi(self)
        self.setAttribute(QtC.Qt.WA_DeleteOnClose, True)
        self.setWindowFlags(self.windowFlags() & ~QtC.Qt.WindowContextHelpButtonHint)

    def init_ui(self) -> None:
        self.setWindowIcon(PySide2.QtGui.QIcon(self.plugin.icon_path))
        icon = QtG.QIcon.fromTheme("preferences")
        self.tb_extra_settings.setIcon(icon)
        self.tb_extra_settings.clicked.connect(self.open_settings_dialog)

        self.cbox_choose_set.setModel(self.model)
        self.cbox_choose_set.setCurrentIndex(self.model.get_active_style_set_index())

        self.ui_ok.setText(self.plugin.tr("Применить"))

    def accept(self) -> None:
        self.model.set_active_style_set(self.cbox_choose_set.currentIndex())
        self.settings_manager.save_style_sets(self.model.get_inner_model_copy_without_default())
        self.settings_manager.apply_style_catalogs_settings()
        QtW.QDialog.accept(self)

    @QtC.Slot()
    def open_settings_dialog(self) -> None:
        dialog = StyleCatalogSettings(self.plugin, self)

        @QtC.Slot(int)
        def finished(_return_code: int):
            self.cbox_choose_set.setCurrentIndex(self.model.get_active_style_set_index())

        dialog.finished.connect(finished)
        dialog.open()
