from PyQt5 import QtWidgets
from PyQt5.QtCore import QThreadPool
from PyQt5 import QtCore

from weissflaechenkartierung.ui.base.WndEventMixIn import BaseShadowMixIn, BaseMoveWindowMixIn, BaseResizeWindowMixIn


class BaseMainWindow(QtWidgets.QMainWindow,
                     BaseShadowMixIn,
                     BaseMoveWindowMixIn,
                     BaseResizeWindowMixIn):
    def __init__(self,
                 dlg=None,
                 save_last_pos: bool = True,
                 shadow: bool = False,
                 move_window: bool = False,
                 resize: bool = False):
        QtWidgets.QMainWindow.__init__(self)

        if self.ui is None:
            raise NameError("the Window has no ui-member. please create a self.ui before you subclass.")

        self.ui.setupUi(self)
        # the constructors need ui elements
        BaseShadowMixIn.__init__(self, dlg=dlg, shadow=shadow)
        BaseMoveWindowMixIn.__init__(self, dlg=dlg, move_window=move_window, save_last_pos=save_last_pos)
        BaseResizeWindowMixIn.__init__(self, dlg=dlg, resize=resize)

        self._thread_pool = QThreadPool()

    def closeEvent(self, event):
        if self.s_l_pos:
            # Write window size and position to config file
            self.dlg.settings.setValue("last_size", self.dlg.size())
            self.dlg.settings.setValue("last_pos", self.dlg.pos())
        event.accept()


class BaseMainDialog(QtWidgets.QDialog,
                     BaseShadowMixIn,
                     BaseMoveWindowMixIn,
                     BaseResizeWindowMixIn):
    """
    class for widgets and dialogs with representing state
    """

    def __init__(self,
                 dlg=None,
                 parent=None,
                 save_last_pos: bool = True,
                 shadow: bool = False,
                 move_window: bool = True,
                 resize: bool = False):
        super(BaseMainDialog, self).__init__(parent)

        if self.ui is None:
            raise NameError("the Window has no ui-member. please create a self.ui before you subclass.")

        self.ui.setupUi(self)
        # the constructors need ui elements

        BaseShadowMixIn.__init__(self, dlg=dlg, shadow=shadow)
        BaseMoveWindowMixIn.__init__(self, dlg=dlg, move_window=move_window, save_last_pos=save_last_pos)
        BaseResizeWindowMixIn.__init__(self, dlg=dlg, resize=resize)

    def resize_to_middle_of_parent(self):
        """
        resizes the dialog to the middle of the parent
        """
        if self.parent():
            p = self.parent().frameGeometry().center() - QtCore.QRect(QtCore.QPoint(), self.sizeHint()).center()
            self.move(p)

    def closeEvent(self, event):
        if self.s_l_pos:
            # Write window size and position to config file
            self.dlg.settings.setValue("last_size", self.dlg.size())
            self.dlg.settings.setValue("last_pos", self.dlg.pos())
        event.accept()
