"""
对指定文件夹中的图片进行加密处理
"""
from ObjectiveC import oc_util
from ObjectiveC import oc_yaml
import os
from PIL import Image  # 添加PIL库用于图片处理 $ pip3 install Pillow 
import io

# 导入自定义工具函数
from ObjectiveC.oc_custom.custom_tools import encrypt_with_random_iv, calculate_file_md5, data_to_hex

def init():
    global file_mix_log
    file_mix_log = open(oc_util.path_mix + "/File混淆日志" + ".txt", "a")

    path = oc_util.path_mix_project
    encrypt_images(path)

def encrypt_images(path):
    """
    遍历指定文件夹，对图片进行加密处理
    """
    for root, dirs, _ in os.walk(path, topdown=True):
        for name in dirs:
            # 如果文件不存在，使用oc_util.name_current_project+'.bundle'
            if name not in oc_yaml.list_image_folder:
                name = oc_util.name_current_project+'.bundle'
                image_path = os.path.join(root, name)
                process_images_in_folder(image_path)
            # 如果文件存在，使用文件名称
            else:
                image_path = os.path.join(root, name)
                process_images_in_folder(image_path)

def process_images_in_folder(image_path):
    """
    处理文件夹中的图片：加密并替换原文件
    """
    for root, _, files in os.walk(image_path, topdown=True):
        for name in files:
            name_list = os.path.splitext(name)
            if name_list[1] in oc_yaml.list_image_type:
                file_path = os.path.join(root, name)
                
                try:
                    # 计算原始文件的 MD5
                    original_md5 = calculate_file_md5(file_path)
                    
                    # 读取图片并转换为标准PNG格式
                    try:
                        # 使用PIL打开图片
                        img = Image.open(file_path)
                        # 将图片转换为PNG格式的二进制数据
                        img_buffer = io.BytesIO()
                        img.save(img_buffer, format='PNG')
                        image_data = img_buffer.getvalue()
                    except Exception as img_error:
                        print(f"转换图片格式失败: {img_error}，使用原始二进制数据")
                        # 如果PIL处理失败，回退到直接读取二进制数据
                        with open(file_path, 'rb') as f:
                            image_data = f.read()
                    
                    # 加密图片数据
                    encrypted_data = encrypt_with_random_iv(image_data)
                    
                    # 构建新文件名（保留原始名称，但删除扩展名）
                    new_file_name = name_list[0]  # 直接使用文件名，不添加任何后缀
                    new_path = os.path.join(root, new_file_name)
                    
                    # 写入加密后的数据 - 使用二进制模式写入
                    with open(new_path, 'wb') as f:
                        f.write(encrypted_data)
                    
                    # 计算加密后文件的 MD5
                    encrypted_md5 = calculate_file_md5(new_path)
                    
                    # 记录原始和加密后的 MD5 值
                    file_mix_log.write('原图:%s-MD5:%s 被修改后MD5:%s\n' % (new_file_name, original_md5, encrypted_md5))
                    
                    # 删除原始文件
                    os.remove(file_path)
                    
                except Exception as e:
                    print(f"加密图片 {file_path} 失败: {e}")