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

import os
from optparse import OptionParser
from xml.dom import minidom
import pyExcelerator

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("-o", "--outputDir",
                      help="输出路径",
                      metavar="outputDir")
    (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_export_untranslate(module_name, module_dir, lang_code, output_dir):
    print("module_export_untranslate, module_name:{0}, module_dir:{1}".format(
        module_name, module_dir))
    all_en_strings = os.path.join(
        module_dir, 'src/main/res/values/strings.xml')
    all_zh_strings = os.path.join(
        module_dir, 'src/main/res/values-zh/strings.xml')
    to_handle_strings = os.path.join(
        module_dir, 'src/main/res/values-{}/strings.xml'.format(lang_code))
    en_strings_dict = read_strings_2_dict(all_en_strings)
    zh_strings_dict = read_strings_2_dict(all_zh_strings)
    to_handle_strings_dict = read_strings_2_dict(to_handle_strings)
    module_untranslate_list = [['keyName', 'en', 'zh']]
    for k, v in en_strings_dict.items():
        if not to_handle_strings_dict.has_key(k):
            zh_value = zh_strings_dict.get(k)
            module_untranslate_list.append([k, v, zh_value])
    if len(module_untranslate_list) <= 1:
        return

    workbook = pyExcelerator.Workbook()
    ws = workbook.add_sheet(module_name)
    row_index = 0
    for row in module_untranslate_list:
        column_index = 0
        for column in row:
            # print("module_export_untranslate, row_index:{0}, column_index:{1}, column:{2}".format(
            #     row_index, column_index, column.encode('utf-8')))
            ws.write(row_index, column_index, column)
            column_index += 1
        row_index += 1
    output_path = os.path.join(output_dir, '{}.xls'.format(module_name))
    workbook.save(output_path)


def export_untranslate(options):
    lang_code = options.langCode
    output_dir = options.outputDir
    cwd = os.getcwd()
    print("export_untranslate, cwd:{0}, lang_code:{1}, output_dir:${2}".format(
        cwd, lang_code, output_dir))
    for dir in FIND_DIDS:
        full_dir = os.path.join(cwd, dir)
        if not os.path.exists(full_dir):
            continue
        if dir == APP_MOUDULE:
            module_export_untranslate(
                APP_MOUDULE, full_dir, lang_code, output_dir)
        else:
            for module in os.listdir(full_dir):
                module_export_untranslate(
                    module, os.path.join(full_dir, module), lang_code, output_dir)


options = option_parser()
export_untranslate(options)
