import cv2

from mower.utils import config
from mower.utils.image import cropimg, diff_ratio, horizontal_stitch
from mower.utils.log import logger
from mower.utils.solver import BaseSolver


def get_whole_scene(draw=False):
    solver = BaseSolver()
    while True:
        img1 = config.recog.gray
        solver.swipe_ext([(100, 870), (1920, 870)], [200], 400, 0.1)
        img2 = config.recog.gray
        if not diff_ratio(img1, img2, thresh=10, ratio=0.2):
            logger.info("滑到头了")
            break
    images = []
    new = cropimg(config.recog.img, ((0, 150), (1920, 880)))
    images.append(new)
    retry_time = 2
    while True:
        solver.swipe_ext([(1820, 870), (1000, 870)], [200], 600, 0.2)
        new = cropimg(config.recog.img, ((0, 150), (1920, 880)))
        gray1 = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
        gray2 = cv2.cvtColor(images[-1], cv2.COLOR_RGB2GRAY)
        flag = diff_ratio(gray1, gray2, thresh=10, ratio=0.2)
        if flag:
            images.append(new)
            retry_time = 1
        elif retry_time:
            retry_time -= 1
        else:
            logger.info("滑到底了")
            break
    logger.info(f"截图读取完了,有{len(images)}张截图")
    if len(images) > 1:
        stitch_img = horizontal_stitch(images)
    else:
        stitch_img = images[0]
    if draw:
        from matplotlib import pyplot as plt

        for img in images:
            plt.imshow(img)
            plt.show()
        plt.imshow(stitch_img)
        plt.show()
    return cv2.GaussianBlur(stitch_img, (5, 5), 0)
