# -*- coding:utf-8 -*-

import os
from optparse import OptionParser
from xml.dom import minidom
import xlrd
import sys
import re

APP_MOUDULE = 'app'
FIND_DIDS = [APP_MOUDULE, 'frame', 'module']


def option_parser():
    parser = OptionParser()
    parser.add_option("-l", "--langCode",
                      help="语言码",
                      metavar="langCode")
    parser.add_option("-i", "--inputDir",
                      help="翻译文件路径",
                      metavar="inputDir")
    (options, _) = parser.parse_args()
    return options


def read_xml_2_dom(path):
    f = open(path, 'r')
    try:
        dom = minidom.parse(f)
        f.close()
        return dom
    except:
        print('xml_2_dom error, path:{}'.format(path))
        f.close()
        return


def read_strings_2_dict(strings_path):
    string_dict = {}
    if not os.path.exists(strings_path):
        return string_dict

    dom = read_xml_2_dom(strings_path)
    if dom == None:
        return

    root = dom.documentElement
    strings = root.getElementsByTagName('string')
    for string in strings:
        translatable = string.getAttribute('translatable')
        if translatable == 'false':
            continue
        key = string.getAttribute('name')
        # print("read_strings_2_dict, key:{0}".format(key))
        value = string.firstChild.data
        string_dict[key] = value
    return string_dict


def module_update_translate(module_name, module_dir, lang_code, input_dir):
    print("module_update_translate, module_name:{0}, module_dir:{1}".format(
        module_name, module_dir))
    # 从xls中读取更新字符串
    update_strings_xls_file_path = os.path.join(
        input_dir, '{}.xls'.format(module_name))
    table = xlrd.open_workbook(
        update_strings_xls_file_path).sheet_by_name(module_name)
    firstRow = table.row_values(0)
    target_lang_col = 0
    for index in range(len(firstRow)):
        if index <= 0:
            continue
        if firstRow[index] == lang_code:
            target_lang_col = index
    keys = table.col_values(0)
    del keys[0]
    values = table.col_values(target_lang_col)
    del values[0]
    update_strings_dic = {}
    for x in range(len(keys)):
        key = keys[x].strip()
        value = re.sub(r'(%\d\$)(@)', r'\1s', values[x])
        update_strings_dic[key] = value

    module_strings = os.path.join(
        module_dir, 'src/main/res/values-{}/strings.xml'.format(lang_code))
    if not os.path.exists(module_strings):
        module_strings_dir = os.path.join(
            module_dir, 'src/main/res/values-{}/'.format(lang_code))
        if not os.path.exists(module_strings_dir):
            os.makedirs(module_strings_dir)
        fo = open(module_strings, "w")
        strings = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n"
        for k, v in update_strings_dic.items():
            strings = strings + "   <string name=\"" + k + "\">" + v + "</string>\n"
        strings = strings + "</resources>"
        fo.write(strings)
        fo.close()
    else:
        module_strings_dict = read_strings_2_dict(module_strings)
        module_strings_fr = open(module_strings, "r")
        # 更新已有字符串
        module_strings_text = module_strings_fr.read()
        module_strings_fr.close()
        insert_strings_dict = {}
        for k, v in update_strings_dic.items():
            if k in module_strings_dict:
                module_strings_text.replace(module_strings_dict[k], v)
            else:
                insert_strings_dict[k] = v
        module_strings_fw = open(module_strings, "w")
        module_strings_fw.write(module_strings_text)
        module_strings_fw.close()

        # 插入新字符串
        module_strings_fr = open(module_strings, "r")
        module_strings_lines = module_strings_fr.readlines()
        module_strings_fr.close()
        start_line_num = -1
        for line_num in range(len(module_strings_lines)):
            if module_strings_lines[line_num].find('</resources>') > -1:
                start_line_num = line_num
                break
        for k, v in insert_strings_dict.items():
            module_strings_lines.insert(
                start_line_num, "   <string name=\"" + k + "\">" + v + "</string>\n")
            start_line_num = start_line_num + 1
        module_strings_fw = open(module_strings, "w")
        module_strings_fw.write(''.join(module_strings_lines))
        module_strings_fw.close()


def update_translate(options):
    lang_code = options.langCode
    input_dir = options.inputDir
    cwd = os.getcwd()
    print("update_translate, cwd:{0}, lang_code:{1}, input_dir:${2}".format(
        cwd, lang_code, input_dir))
    module_include_dir_dict = {}
    for dir in FIND_DIDS:
        if dir != APP_MOUDULE:
            full_dir = os.path.join(cwd, dir)
            for module in os.listdir(full_dir):
                module_include_dir_dict[module] = dir
    for file_name in os.listdir(input_dir):
        if not file_name.endswith(".xls"):
            continue
        module = file_name.split('.')[0]
        if module == "":
            continue
        if module == APP_MOUDULE:
            module_update_translate(APP_MOUDULE, os.path.join(
                cwd, APP_MOUDULE), lang_code, input_dir)
        else:
            dir = module_include_dir_dict[module]
            module_include_dir = os.path.join(cwd, dir)
            module_update_translate(module, os.path.join(
                module_include_dir, module), lang_code, input_dir)


options = option_parser()
update_translate(options)
