from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QSettings, QSize, QPoint, Qt
from PyQt5.QtWidgets import QGraphicsDropShadowEffect, QSizeGrip

from weissflaechenkartierung.res.styles import COLOR


class BaseShadowMixIn:
    def __init__(self, dlg=None, shadow: bool = False):
        if shadow and dlg:
            if isinstance(dlg, QtWidgets.QMainWindow):
                dlg.setWindowFlags(QtCore.Qt.FramelessWindowHint)
            else:
                dlg.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.FramelessWindowHint)
            dlg.setAttribute(QtCore.Qt.WA_TranslucentBackground)

            self.shadow = QGraphicsDropShadowEffect()
            self.shadow.setBlurRadius(COLOR.SHADOW_RANGE)
            self.shadow.setXOffset(0)
            self.shadow.setYOffset(0)
            self.shadow.setColor(COLOR.SHADOW_BASE_COLOR)

            try:
                dlg.ui.shadow.setGraphicsEffect(self.shadow)
            except (NameError, AttributeError):
                raise NameError("dlg.ui.shadow_frame not found")


class BaseMoveWindowMixIn:
    def __init__(self, dlg=None, move_window: bool = True, save_last_pos: bool = True):
        if move_window and dlg:
            self.dlg = dlg
            self.dragPos = 0
            self.s_l_pos = save_last_pos
            if save_last_pos:
                self.dlg.settings = QSettings(self.__class__.__name__, self.__class__.__name__)
                dlg.resize(self.dlg.settings.value("last_size", QSize(dlg.height(), dlg.width())))
                dlg.move(self.dlg.settings.value("last_pos", QPoint(380, 230)))
            try:
                dlg.ui.frame_top_title.mouseMoveEvent = dlg.move_window
            except NameError:
                raise NameError("dlg.ui.frame_top_title not found")

            try:
                dlg.mousePressEvent = dlg.mouse_press_event
            except Exception as e:
                raise Exception(e.__str__())

    def move_window(self, event):
        if event.buttons() == Qt.LeftButton:
            self.dlg.move(self.dlg.pos() + event.globalPos() - self.dragPos)
            self.dragPos = event.globalPos()
            event.accept()

    def mouse_press_event(self, event):
        self.dragPos = event.globalPos()


class BaseResizeWindowMixIn:
    def __init__(self, dlg=None, resize: bool = True):
        if resize and dlg:
            try:
                dlg.sizegrip = QSizeGrip(dlg.ui.frame_size_grip)
                dlg.sizegrip.setStyleSheet("width: 20px; height: 20px; margin 0px; padding: 0px;")
            except NameError:
                raise NameError("dlg.ui.frame_size_grip not found")
