'''
Author: deng.yinping deng.yinping@muchinfo.cn
Date: 2025-03-07 16:27:53
LastEditors: deng.yinping deng.yinping@muchinfo.cn
LastEditTime: 2025-03-11 13:56:49
FilePath: \MTP20_i18n_Tool\src\service_tools.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''

from src.common import CommonUti
import os
import re

class Service_Tools:
        
    @staticmethod
    def generate_excel(oem, inc_file, output_folder, json_folder, oem_json_folder):
        '''
        根据properties文件生成excel文件
        '''
        Service_Tools.generate_excle(oem, output_folder, json_folder, oem_json_folder)
        # 增量更新，在生成excel里标注新增的key为黄色
        CommonUti.update_excel_by_inc(oem, output_folder, inc_file)
        
    @staticmethod
    def generate_properties(oem, output_folder, json_folder, oem_json_folder):
        '''
        根据excel生成properties文件
        '''
        dic_cn, dic_en, dic_th, dic_tw, dic_vi = CommonUti.read_from_excel(oem, output_folder)
        Service_Tools.generate_excle(oem, dic_cn, 'zh-cn', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_excle(oem, dic_en, 'en', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_excle(oem, dic_th, 'th', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_excle(oem, dic_tw, 'zh-tw', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_excle(oem, dic_vi, 'vi', output_folder, json_folder, oem_json_folder)
        
    @staticmethod
    def generate_excle(oem, output_folder, json_folder, oem_json_folder):
        # 据JSON生成excel文件
        zh_data = Service_Tools.read_data_from_properties(
            oem, json_folder, oem_json_folder, 'zh-cn')
        en_data = Service_Tools.read_data_from_properties(
            oem, json_folder, oem_json_folder, 'en')
        th_data = Service_Tools.read_data_from_properties(
            oem, json_folder, oem_json_folder, 'th')
        tw_data = Service_Tools.read_data_from_properties(
            oem, json_folder, oem_json_folder, 'zh-tw')
        vi_data = Service_Tools.read_data_from_properties(
            oem, json_folder, oem_json_folder, 'vi')

        CommonUti.generate_excle_by_oem(
            oem, output_folder, zh_data, en_data, th_data, tw_data, vi_data)
    
    @staticmethod
    def read_data_from_properties(oem, json_folder, oem_json_folder, lang):
        common_file = json_folder + 'message_' + lang + '.properties'
       
        # 处理OEM数据
        properties_dict = {}
        with open(common_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()  # 去除首尾空白字符
                if not line or line.startswith(('#', '!')):  # 跳过空行和注释
                    continue
                # 分割键值对（处理可能存在多个等号的情况）
                key_value = line.split('=', 1) if '=' in line else line.split(':', 1)
                if len(key_value) != 2:
                    continue  # 无效行跳过
                key, value = key_value[0].strip(), key_value[1].strip()
                # 处理转义字符（例如 \n 或 \t）
                # 判断是否java unicode 转义格式
                if (Service_Tools.is_unicode_escape(value)):
                    value = value.encode('utf-8').decode('unicode_escape')
                properties_dict[key] = value
                
        return properties_dict

    
    @staticmethod
    def generate_properties_files(oem, output_folder, json_folder, oem_json_folder):
        '''
        根据excel生成JSON文件
        '''
        dic_cn, dic_en, dic_th, dic_tw, dic_vi = CommonUti.read_from_excel(oem, output_folder)
        Service_Tools.generate_properties(oem, dic_cn, 'zh-cn', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_properties(oem, dic_en, 'en', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_properties(oem, dic_th, 'th', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_properties(oem, dic_tw, 'zh-tw', output_folder, json_folder, oem_json_folder)
        Service_Tools.generate_properties(oem, dic_vi, 'vi', output_folder, json_folder, oem_json_folder)
        
    @staticmethod
    def generate_properties(oem, excel_dic, lang, output_folder, json_folder, oem_json_folder): 
        # OEM输出文件地址
        oem_output = output_folder + '/resources/message_' + lang + '.properties'
      
        if os.path.exists(oem_output):  # 检查文件是否存在[4,10](@ref)
            os.remove(oem_output)       # 存在则删除[9,10](@ref)
            
        # with open(oem_output, 'w', encoding='ISO-8859-1') as f:
        with open(oem_output, 'w', encoding='utf-8') as f:
            for key, value in excel_dic.items():
                # 处理转义字符（如 \n → \\n，等号 → \=）
                escaped_value = value.replace('\n', '\\n').replace('=', '\\=')
                # 转义为unicode
                # escaped_value = escaped_value.encode('unicode_escape').decode('utf-8')
                
                f.write(f"{key}={escaped_value}\n")
                
        print("%s JSON文件已成功输出到 %s" % (lang, oem_output))
     
    @staticmethod   
    def is_unicode_escape(value):
        # 判断是否java unicode 转义格式
        return bool(re.search(r'\\u[0-9A-Fa-f]{4}', value))