# @Author  : lightXu
# @File    : segment.py
import os

import xml.etree.cElementTree as ET

from segment.image_operation import utils


def joint_image(raw_img_path, bbox, lines_list):
    lines_dir = raw_img_path.replace('.jpg', '_lines')
    lines_file_list = os.listdir(lines_dir)
    lines_file_list = sorted([ele.replace('jpg', '')
                              for ele in lines_file_list if ele.endswith('.jpg')])

    exam_items_bbox = []

    tree = ET.parse(r'./segment/exam_info/000000-template.xml')  # xml tree
    for index_num, j in enumerate(lines_list):
        if j[1] == j[0]:
            continue
        elif j[1] - j[0] == 1:
            index_list = lines_file_list[j[0]].split('_')
            y_low = int(index_list[0])
            y_high = int(index_list[1])
            x_low = int(index_list[2])
            x_high = int(index_list[3])
        else:
            index_list0 = lines_file_list[j[0]].split('_')  # [33, 37]
            index_list1 = lines_file_list[j[1] - 1].split('_')
            y_low = int(index_list0[0])
            y_high = int(index_list1[1])

            tmp_x_low_list = [ele.split('_')[2]
                              for ele in lines_file_list[j[0]:j[1]]]
            tmp_x_high_list = [ele.split('_')[3]
                               for ele in lines_file_list[j[0]:j[1]]]
            x_low = int(min(tmp_x_low_list))
            x_high = int(max(tmp_x_high_list))
        exam_bbox = [bbox[2] + x_low, bbox[0] + y_low, bbox[2] + x_high, bbox[0] + y_high]

        tree = utils.create_xml('{:02d}'.format(index_num), tree,
                                exam_bbox[0], exam_bbox[1], exam_bbox[2], exam_bbox[3])
        exam_items_bbox.append(exam_bbox)
    # print(exam_items_bbox)
    tree.write(raw_img_path.replace('.jpg', '.xml'))
    return exam_items_bbox
