"""Mouse handlers for exclusion rectangles."""

from __future__ import annotations


class ExclusionMixin:
    """Manage exclusion rectangles drawn on the preview canvas."""

    def _exclude_start(self, event):
        if self.preview_img is None:
            return
        x = max(0, min(self.preview_img.width - 1, int(event.x)))
        y = max(0, min(self.preview_img.height - 1, int(event.y)))
        self._rubber_start = (x, y)
        if self._rubber_id:
            try:
                self.canvas_orig.delete(self._rubber_id)
            except Exception:
                pass
        self._rubber_id = self.canvas_orig.create_rectangle(x, y, x, y, outline="yellow", width=2)

    def _exclude_drag(self, event):
        if not self._rubber_start:
            return
        x0, y0 = self._rubber_start
        x1 = max(0, min(self.preview_img.width - 1, int(event.x)))
        y1 = max(0, min(self.preview_img.height - 1, int(event.y)))
        self.canvas_orig.coords(self._rubber_id, x0, y0, x1, y1)

    def _exclude_end(self, event):
        if not self._rubber_start:
            return
        x0, y0 = self._rubber_start
        x1 = max(0, min(self.preview_img.width - 1, int(event.x)))
        y1 = max(0, min(self.preview_img.height - 1, int(event.y)))
        rx0, rx1 = sorted((x0, x1))
        ry0, ry1 = sorted((y0, y1))
        if (rx1 - rx0) > 0 and (ry1 - ry0) > 0:
            self.exclude_rects.append((rx0, ry0, rx1, ry1))
        self._rubber_start = None
        self._rubber_id = None
        self.update_preview()

    def clear_excludes(self):
        self.exclude_rects = []
        self.canvas_orig.delete("all")
        if self.preview_tk:
            self.canvas_orig.create_image(0, 0, anchor="nw", image=self.preview_tk)
        self.update_preview()

    def undo_exclude(self):
        if self.exclude_rects:
            self.exclude_rects.pop()
            self.update_preview()


__all__ = ["ExclusionMixin"]
