import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import PIL


def parse_gt_file(path):
    gt_res = []
    with open(path, "r") as file:
        while True:
            line = file.readline()
            if not line:
                break
            arr = line.split(",")
            coo = arr[:8]
            content = ",".join(arr[8:])
            pair = ([int(i) for i in coo], content)
            gt_res.append(pair)
    return gt_res


def write_gt_to_file(gt, file_path):
    with open(file_path, "w") as file:
        for index in range(len(gt)):
            ele = gt[index]
            coo = ",".join([str(e) for e in ele[0]])
            content = ele[1]
            file.write("%s,%s\n" % (coo, content))


def pil_to_cv(pil_img):
    return cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)


def visualization(img, dets=None, gts=None, font_path='/System/Library/Fonts/PingFang.ttc', font_size=18, font_size_adaptive=False):
    origin_type = 0
    main_pic = None
    if isinstance(img, PIL.Image.Image):
        main_pic = img
        origin_type = 1
    elif isinstance(img, np.ndarray):
        main_pic = Image.fromarray(img)
        origin_type = 2

    if main_pic is None or origin_type == 0:
        return main_pic

    gt_part = None
    det_part = None
    if gts is not None:
        # 真值框开启文字大小自适应
        main_pic, gt_part = draw_pic(main_pic, gts, font_path, font_size, 'red', font_size_adaptive)
    if dets is not None:
        # 检测框不开启自适应
        main_pic, det_part = draw_pic(main_pic, dets, font_path, font_size, 'green', font_size_adaptive)

    result = main_pic
    if gt_part is not None:
        result = combine(gt_part, result)
    if det_part is not None:
        result = combine(result, det_part)

    if origin_type == 2:
        result = cv2.cvtColor(np.asarray(result), cv2.COLOR_RGB2BGR)

    return result


# 将两张图合到一张图上
def combine(left_img, right_img):
    w1, h1 = left_img.size
    w2, h2 = right_img.size
    canvas = Image.new('RGB', (w1 + w2, max(h1, h2)), (255, 255, 255))
    canvas.paste(left_img, (0, 0, w1, h1))
    canvas.paste(right_img, (w1, 0, w1 + w2, h2))
    return canvas


def draw_pic(img, tuples, font_path, font_size, color='red', size_fit_area=False):
    draw = ImageDraw.Draw(img)
    contrast = Image.new('RGB', img.size, (255, 255, 255))
    contrast_draw = ImageDraw.Draw(contrast)

    for index in range(len(tuples)):
        rectangle = tuples[index][0]
        content = tuples[index][1]
        draw.line([tuple((rectangle[0], rectangle[1])),
                   tuple((rectangle[2], rectangle[3])),
                   tuple((rectangle[4], rectangle[5])),
                   tuple((rectangle[6], rectangle[7])),
                   tuple((rectangle[0], rectangle[1]))], width=2, fill=color)
        if font_size < 0:
            font_size = 18
        font = ImageFont.truetype(font_path, font_size)
        # 文字大小适配检测框（按文字区域高度）
        if size_fit_area:
            area_height = min(rectangle[7] - rectangle[1], rectangle[5] - rectangle[3])
            area_height = max(area_height, - area_height)
            # print(area_height)
            while font.getsize('国')[0] < area_height:
                font_size += 1
                font = ImageFont.truetype(font_path, font_size)
            while font.getsize('国')[0] > area_height:
                font_size -= 1
                font = ImageFont.truetype(font_path, font_size)
        contrast_draw.text((rectangle[0], rectangle[1]), text=content, fill=(0, 0, 0), font=font)
    contrast_draw.text((img.size[0] / 2 - 10, 0), text=color, fill=color, font=ImageFont.truetype(font_path, 26))
    return img, contrast

