import cv2
import numpy as np

from mower.utils.image import cropimg, load_static

drone_template = [load_static(f"drone_count/{i}", True) for i in range(10)]
time_template = [load_static(f"orders_time/{i}", True) for i in range(10)]


def get_drone(gray):
    gray = cropimg(gray, ((1144, 32), (1225, 76)))
    result = {}
    for j in range(10):
        res = cv2.matchTemplate(gray, drone_template[j], cv2.TM_CCORR_NORMED)
        threshold = 0.95
        loc = np.where(res >= threshold)
        for i in range(len(loc[0])):
            offset = loc[1][i]
            accept = True
            for o in result:
                if abs(o - offset) < 5:
                    accept = False
                    break
            if accept:
                result[loc[1][i]] = j
    return int("".join([str(result[k]) for k in sorted(result)]))


def get_time(gray):
    gray = cropimg(gray, ((499, 510), (1920, 543)))
    result = {}
    for i in range(10):
        res = cv2.matchTemplate(gray, time_template[i], cv2.TM_CCOEFF_NORMED)
        threshold = 0.85
        loc = np.where(res >= threshold)
        for i in range(len(loc[0])):
            x = loc[1][i]
            accept = True
            for o in result:
                if abs(o - x) < 5:
                    accept = False
                    break
            if accept:
                if len(result) == 0:
                    gray = gray[:, loc[1][i] - 5 : loc[1][i] + 116]
                    offset = loc[1][0] - 5
                    for m in range(len(loc[1])):
                        loc[1][m] -= offset
                result[loc[1][i]] = i
    ch = [str(result[k]) for k in sorted(result)]
    return f"{ch[0]}{ch[1]}:{ch[2]}{ch[3]}:{ch[4]}{ch[5]}"
