import os
import re
awtk = 'awtk'
flything = 'flything'
xml_s = []
head_s = []
# 从配置文件中，读取信息
with open('./check_img_config.txt', encoding="utf-8") as f:
    # 读取编译类型
    compile_tyep = f.readline().lower()[:-1]
    if not compile_tyep in ['flything', 'awtk']:
        print(f"error:compile type:'{compile_tyep}' is mistake!!")
        exit()
    # 读取图片路径
    pic_path = f.readline()[:-1]
    pic_path = pic_path.split('|')
    for pic_path_i in pic_path:
        if not os.path.exists(pic_path_i):
            print(f"error:image's path:'{pic_path}' is inexistence!!")
            exit()
    # 读取资源文件路径（awtk）
    xml_or_path_head = f.readline()[:-1]
    if compile_tyep == awtk:
        xml_or_path_head = xml_or_path_head.split('|')
    # 读取路径头
    # 读取代码路径
    codes_path = f.readline()[:-1]
    if not os.path.exists(codes_path):
        print(f"error:code's path:'{codes_path}' is inexistence!!")
        exit()
    # 读取%s的信息
    format_info = f.readline()[:-1]
    if '|' in format_info:
        format_info = format_info.split('|')
    else:
        format_info = [i for i in format_info]
    # 读取排除的信息
    exclude_infos = [i for i in f.readline().split("|")]
def find_image(root_path, image_name):
    # # 遍历指定路径及其子目录
    # for root, dirs, files in os.walk(root_path):
    #     # 检查当前目录中文件列表
    #     if image_name in files:
    #         # 如果找到图片，返回完整路径
    #         return os.path.join(root, image_name)
    # # 如果未找到，则返回None
    # return None
    if os.path.exists(root_path + image_name):
        return True
    else:
        # print(root_path + image_name)
        return None  # 未找到文件，返回None
def check_image(image_path:str):
    if '%d' in image_path:
        for i in range(10):
            check_image(image_path.replace('%d', f'{i}', 1))
        return
    elif '%s' in image_path:
        for i in format_info:
            check_image(image_path.replace('%s', f'{i}', 1))
        return
    elif '%u' in image_path:
        for i in range(10):
            check_image(image_path.replace('%u', f'{i}', 1))
        return
    flag_pic_inexistence_path = 0
    for pic_path_i in pic_path:
        if compile_tyep == awtk:
            if not find_image(pic_path_i+'\\', image_path) and image_path not in exclude_infos:
                # print(f"图片{image_path}不存在[{pic_path_i}]")
                flag_pic_inexistence_path+=1
            # else:
                # print(f"图片 {image_path} 存在")
        elif compile_tyep == flything:
            if not find_image(pic_path_i, image_path) and image_path not in exclude_infos:
                for head in head_s:
                    if find_image(pic_path_i, head+image_path):
                        continue
                    else:
                        print(f"图片{head+image_path}不存在")
            # else:
                # print(f"图片 {image_path} 存在")
    if compile_tyep == awtk:
        if flag_pic_inexistence_path == len(pic_path):
            print(f"图片{image_path}不存在")
# 读取awtk文件的内容
if compile_tyep == 'awtk':
    for xml_i in xml_or_path_head:
        with open(xml_i, encoding='utf-8') as xml_f:
            xml_data = xml_f.read()
        # for xml_line in xml_data.split('<'):
        ctl_name = re.findall('<.*?name="(.*?)"', xml_data)
        if ctl_name:
            xml_s+=ctl_name
elif compile_tyep == 'flything':
    # 处理路径头
    for path_i in xml_or_path_head.split('|'):
        head_s.append(path_i)
    pass
def check_code_to_imgs(code_file):
    img_names = []
    try:
        with open(code_file, encoding='utf-8') as cf:
            content = cf.read()
    except:
        with open(code_file, encoding='gbk') as cf:
            content = cf.read()
    # 使用正则表达式来匹配图片路径
    # image_paths = re.findall(r"(.*?\.(jpg|jpeg|png|gif))", content)
    # image_paths = re.findall('"(.*?)"', content)
    for cont_line in content.split('\n'):
        if not cont_line.strip() or cont_line.strip()[:2] == '//' or cont_line.strip()[0] == '#' or ("printf" in cont_line and "sprintf" not in cont_line) or "extern" in cont_line or cont_line.strip()[0] == '*' or cont_line.strip()[:4] == 'LOGD':
            continue
        image_paths = re.findall('"(.*?)"', cont_line)
        if compile_tyep == awtk:
            for str_image_or_ctl in image_paths:
                if str_image_or_ctl in exclude_infos:
                    continue
                if not str_image_or_ctl in xml_s:
                    # if str_image_or_ctl.strip()[:2] == '//':
                    img_names.append(str_image_or_ctl +".png")
        elif compile_tyep == flything:
            for str_image_or_ctl in image_paths:
                if str_image_or_ctl in exclude_infos:
                    continue
                img_names.append(str_image_or_ctl)
    return img_names
# print(compile_tyep,pic_path,codes_path,format_info)
# 查找代码路径下所有的文件
if __name__ == '__main__':
    for root, dirs, files in os.walk(codes_path):
        # print(files)
        # print(fles)
        for file_item in files:
            if os.path.splitext(file_item)[-1][1:] in ["cc", "c", "cpp", "h"]:
                for img in check_code_to_imgs(root + '\\' + file_item):
                    check_image(img)
