from translater import translate
from file_scanner import scan_directory
import decorator
import file_util
import time
import sys
import json


def trans(lines):
    """
    读取和翻译文件
    :param file_name: 文件名
    :return:
    """
    trans_result = ""
    # TODO 字符串是否是不可改变的？
    waiting_trans = ""
    for line in lines:
        # TODO 改成正则匹配
        if line.lstrip().startswith('*') or line.lstrip().startswith('/*') or line.lstrip().startswith('*/'):
            # 添加当前行
            trans_result += line
            waiting_trans += line
        else:
            # 查询翻译结果
            if len(waiting_trans) != 0:
                # 查看第一行注释开头的空格数, 因为有可能是\t制表符
                space_index = waiting_trans.index('/')
                space_content = waiting_trans[0:space_index]
                deco = decorator.before_trans(waiting_trans)
                # 添加异常处理是为了定位异常来源
                try:
                    trans_res = translate(deco)
                    # 添加翻译结果
                    trans_result += decorator.after(trans_res, space_content)
                except json.decoder.JSONDecodeError as e:
                    print("翻译内容是：")
                    print(deco)
                    raise e

            # 添加不用翻译的当前行
            trans_result += line
            # 待翻译置为空
            waiting_trans = ""
    return trans_result

# 使用此标题进行错误恢复
head = "/** Generated by english-annotation-buster, Powered by Google Translate.**/\n"
def i_am_buster(source_dir):
    # 错误恢复，翻译到一半挂了恢复, 直接在开头加一段注释，读文件读到该注释，直接跳过
    # TODO 文件太多，多进程翻译（貌似python多线程就是个渣渣）
    """

    :param source_dir: 项目文件夹
    :return:
    """
    files = scan_directory(source_dir)
    for file_name in files:
        # 去除source_dir，使得显示更加舒适
        short_file_name = file_name[len(source_dir):]
        lines = file_util.read_file(file_name)
        if len(lines) != 0 and lines[0].startswith(head):
            print("跳过对文件", short_file_name, "的翻译。")
            continue
        print("开始翻译：" + short_file_name)
        trans_result = trans(lines)
        trans_result = head + trans_result
        file_util.write_back(trans_result, file_name)
        print("完成对 " + short_file_name + " 的翻译")
        time.sleep(1)


def print_usage():
    """
    打印使用信息
    """
    print('Usage: python main.py [path to your java source folder]')
    print('\nExamples:')
    print('\tpython main.py C:\\path\\to\\your\\java\\source\\folder')
    print('\tpython main.py /home/user/path/to/your/java/source/folder')

if __name__ == "__main__":
    # 添加对命令行的解析，如果目前用不着可以先注释它
    if len(sys.argv) < 2:
        print_usage()
        exit()
    code_path = sys.argv[1]
    i_am_buster(code_path)
