import functools

from qgis.PyQt.QtCore import Qt


class QLabelMouseEvent:
    def __init__(self, label, legend, canvas):
        super(QLabelMouseEvent, self).__init__()
        global LEGEND, CANVAS, LABEL
        LEGEND = legend
        CANVAS = canvas
        LABEL = label

        LABEL.setCursor(Qt.SplitHCursor)

        self.startPoint = 0
        self.legendWidth = 0
        self.canvasWidth = 0
        self.casvasX = 0
        self.labelX = 0

        LABEL.mousePressEvent = functools.partial(QLabelMouseEvent.press, self)
        LABEL.mouseReleaseEvent = functools.partial(QLabelMouseEvent.release, self)
        LABEL.mouseMoveEvent = functools.partial(QLabelMouseEvent.move, self)

    def press(self, e):
        self.startPoint = e.pos().x()
        self.legendWidth = LEGEND.geometry().width()
        self.canvasWidth = CANVAS.geometry().width()
        self.casvasX = CANVAS.geometry().x()
        self.labelX = LABEL.geometry().x() - self.casvasX

    def release(self, e):
        self.legendWidth = LEGEND.geometry().width()
        self.canvasWidth = CANVAS.geometry().width()
        self.casvasX = CANVAS.geometry().x()
        self.labelX += self.casvasX
        lbBaseGm = LABEL.geometry()
        LABEL.setGeometry(
            self.labelX, lbBaseGm.y(), lbBaseGm.width(), lbBaseGm.height()
        )

    def move(self, e):
        moves = e.pos().x() - self.startPoint

        lgBaseGm = LEGEND.geometry()
        cvBaseGm = CANVAS.geometry()
        lgCgWidth = self.legendWidth + moves
        cvCgWidth = self.canvasWidth - moves

        if lgCgWidth > 0 and cvCgWidth > 0:
            LEGEND.setGeometry(lgBaseGm.x(), lgBaseGm.y(), lgCgWidth, lgBaseGm.height())
            CANVAS.setGeometry(
                self.casvasX + moves, cvBaseGm.y(), cvCgWidth, cvBaseGm.height()
            )
