from copy import deepcopy

import glog
import os, cv2, json

import numpy as np


def traverse_folder(folder_path, file_list, end=".jpg", all_floder = False):
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        if os.path.isfile(item_path):
            if item_path.endswith(".jpg") or item_path.endswith(".png"):
                file_list.append(item_path)
        elif os.path.isdir(item_path):
            if all_floder is True:
                traverse_folder(item_path, file_list)


def mergeNewImage(img0, etc0, img1, etc1, img2, etc2, img3, etc3):
    img = np.zeros((960, 1280, 3), dtype=np.uint8)
    img[0: 480, 0: 640, 0:3] = img0
    img[0: 480, 640: 1280, :] = img1
    img[480: 960, 0: 640, :] = img2
    img[480: 960, 640: 1280, :] = img3

    if not etc1 is None:
        for point in etc1["points"]:
            point[0] = point[0] + 640
    if not etc2 is None:
        for point in etc2["points"]:
            point[1] = point[1] + 480
    if not etc3 is None:
        for point in etc3["points"]:
            point[0] = point[0] + 640
            point[1] = point[1] + 480
    return img, etc0, etc1, etc2, etc3


def convertImg(file, output_path):
    etc = {}
    ext = os.path.splitext(file)  # 将文件名路径与后缀名分开
    file_name = ext[0].split("/")[-1]
    save_file = output_path + file_name
    json_file = ext[0] + ".json"
    if os.path.isfile(json_file):
        f = open(json_file, 'r')
        content = f.read()
        etc = json.loads(content)
    else:
        return

    img = cv2.imread(file)
    img_lf = img[0: 480, 0: 640, 0:]
    img_rf = img[0: 480, 640: 1280, :]
    img_lr = img[480: 960, 0: 640, :]
    img_rr = img[480: 960, 640: 1280, :]

    etc_sig_old = [None, None, None, None]
    for points in etc['shapes']:
        index = int(points["points"][0][0] // 640) | int(int(points["points"][0][1] // 480) << 1)
        for point in points["points"]:
            point[0] = point[0] % 640
            point[1] = point[1] % 480
        etc_sig_old[index] = points

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_rf, etc_sig[1],
                                                                                                  img_lf, etc_sig[0],
                                                                                                  img_lr, etc_sig[2],
                                                                                                  img_rr, etc_sig[3])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_a.jpg"
    cv2.imwrite(save_file + "_convert_test_a.jpg", merge_img)
    with open(save_file + "_convert_test_a.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_lr, etc_sig[2],
                                                                                                  img_rf, etc_sig[1],
                                                                                                  img_lf, etc_sig[0],
                                                                                                  img_rr, etc_sig[3])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_b.jpg"
    cv2.imwrite(save_file + "_convert_test_b.jpg", merge_img)
    with open(save_file + "_convert_test_b.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_rr, etc_sig[3],
                                                                                                  img_rf, etc_sig[1],
                                                                                                  img_lr, etc_sig[2],
                                                                                                  img_lf, etc_sig[0])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_c.jpg"
    cv2.imwrite(save_file + "_convert_test_c.jpg", merge_img)
    with open(save_file + "_convert_test_c.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_lf, etc_sig[0],
                                                                                                  img_lr, etc_sig[2],
                                                                                                  img_rf, etc_sig[1],
                                                                                                  img_rr, etc_sig[3])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_d.jpg"
    cv2.imwrite(save_file + "_convert_test_d.jpg", merge_img)
    with open(save_file + "_convert_test_d.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_lf, etc_sig[0],
                                                                                                  img_rr, etc_sig[3],
                                                                                                  img_lr, etc_sig[2],
                                                                                                  img_rf, etc_sig[1])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_e.jpg"
    cv2.imwrite(save_file + "_convert_test_e.jpg", merge_img)
    with open(save_file + "_convert_test_e.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)

    etc['shapes'].clear()
    etc_sig = deepcopy(etc_sig_old)
    etc_sig_last = [None, None, None, None]
    merge_img, etc_sig_last[0], etc_sig_last[1], etc_sig_last[2], etc_sig_last[3] = mergeNewImage(img_lf, etc_sig[0],
                                                                                                  img_rf, etc_sig[1],
                                                                                                  img_rr, etc_sig[3],
                                                                                                  img_lr, etc_sig[2])
    for last_etc in etc_sig_last:
        if not last_etc is None:
            etc['shapes'].append(last_etc)
    etc['imagePath'] = file_name + "_convert_test_f.jpg"
    cv2.imwrite(save_file + "_convert_test_f.jpg", merge_img)
    with open(save_file + "_convert_test_f.json", "w") as w_f:
        json.dump(etc, w_f, indent=4)


if __name__ == '__main__':
    path = "/home/zx/DataAcquisition-Python/Modules/moreSpecimens/image"
    output_path = path + "/output/"
    if not os.path.exists(output_path):
        os.mkdir(output_path)
    file_list = []
    # 加载配置
    if os.path.isdir(path):
        traverse_folder(path, file_list)
    else:
        print("it's a special file(socket,FIFO,device file)")
        exit(0)

    for file in file_list:
        print(file)
        if file.endswith(".png"):
            mat = cv2.imread(file)
            # os.remove(file)
            ext = os.path.splitext(file)
            file = ext[0] + ".jpg"
            cv2.imwrite(file, mat)
        convertImg(file, output_path)
