import numpy as np
import cv2 as cv
from random import randint


class Painter:
    def __init__(self) -> None:
        self.mouse_is_pressed = False
        self.last_pos = (-1, -1)
        self.width = 300
        self.height = 512
        self.img = np.zeros((self.width, self.height, 3), np.uint8)
        self.window_name = 'painter'
        self.color = None

    def run(self):
        print('画板，拖动鼠标绘制矩形框，按ESC退出，按c键清空画板')
        cv.namedWindow(self.window_name)
        cv.setMouseCallback(
            self.window_name,
            lambda event, x, y, flags, param: self.on_draw(
                event, x, y, flags, param
            )
        )
        while True:
            cv.imshow(self.window_name, self.img)
            k = cv.waitKey(1) & 0xFF
            if k == ord('c'):
                self.clean()
            elif k == 27:
                break

        cv.destroyAllWindows()

    def on_draw(self, event, x, y, flags, param):
        pos = (x, y)
        if event == cv.EVENT_LBUTTONDOWN:
            self.mouse_is_pressed = True
            self.last_pos = pos
        elif event == cv.EVENT_MOUSEMOVE:
            if self.mouse_is_pressed == True:
                self.begin_draw_rectangle(self.last_pos, pos)
        elif event == cv.EVENT_LBUTTONUP:
            self.end_draw_rectangle(self.last_pos, pos)
            self.mouse_is_pressed = False

    def clean(self):
        cv.rectangle(self.img, (0, 0),
                     (self.height, self.width), (0, 0, 0), -1)

    def begin_draw_rectangle(self, pos1, pos2):
        if self.color is None:
            self.color = (randint(0, 256), randint(0, 256), randint(0, 256))
        cv.rectangle(self.img, pos1, pos2, self.color, -1)

    def end_draw_rectangle(self, pos1, pos2):
        self.color = None


if __name__ == '__main__':
    p = Painter()
    p.run()
