#!/usr/bin/env python3
import json
import string
import random
import glob, os
import sys


def get_brackets(line):
    left = line.count("{")
    right = line.count("}")
    return left - right


def code_loanapplyfragment(path):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        # readlines以列表的形式将文件读出
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        flag1 = False
        flag2 = False
        flag3 = False
        flag4 = False
        brackets = 0
        for line in lines:

            if "getPresenter(LoanPresenter.class).checkQualification(\"action_checkQualification\");" in line:
                code = "\n\t\t\t\t\tnew LoanApplyProxy(getActivity(), this, productBean).startLoan(basicAck -> {\n" + \
                       "\t\t\t\t\t\tnew EventSender.Builder(MessageID.LOAN_STATUS_CHANGED).build().sendEvent();\n" + \
                       "\t\t\t\t\t});\n"
                line = "// " + line + code;

            # 3
            if "case \"action_checkQualification\":" in line:
                flag3 = True
            if flag3:
                flag3 = "// " + line
            if "break;" in line:
                flag3 = False;

            # 2
            if "case \"action_faceVerify\":" in line:
                flag2 = True
            if flag2:
                line = "// " + line
            if "break;" in line:
                flag2 = False;

            # 1
            if "public void startFaceVerify() {" in line:
                flag1 = True
                brackets = get_brackets(line)

            if flag1 and brackets > 0:
                line = "// " + line
                brackets += get_brackets(line)
            f_w.write(line)
    print ("code_LoanAppFragment updated !")
    return


def code_certifyactivity(path):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        # readlines以列表的形式将文件读出
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        for line in lines:
            if "setTopBarTitle(getString(R.string.text_certification));" in line:
                code = "\n\t\tButton nextStepBtn = findViewById(R.id.activity_certify_next_btn);\n" + \
                       "\t\tif (!TextUtils.isEmpty(BuildConfig.TONGDUN_PARENT_KEY)) {\n" + \
                       "\t\t\tnextStepBtn.setVisibility(View.VISIBLE);\n" + \
                       "\t\t\tnextStepBtn.setOnClickListener(v -> {\n" + \
                       "\t\t\t\tCertifyProgressActivity.start(CertifyActiviy.this, CertifyProgressActivity.CertifyType.CERTIFY_ACCOUNT);\n" + \
                       "\t\t\t});\n" + \
                       "\t\t}\n\n"
                line = line + code

            f_w.write(line)
    print ("code_CertifyActivity updated !")
    return


def code_fragments(path):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        # readlines以列表的形式将文件读出
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        for line in lines:
            if "startFragment(PersonalInfoFragment.create(mGenderBtn.getText().toString()), true);" in line:
                code = "\n\t\t\t\t\t\t\tnew EventSender.Builder(MessageID.CERTIFY_PROGRESS_CHANGED).obj(PersonalInfoFragment.create(mGenderBtn.getText().toString())).build().sendEvent();\n"
                line = "// " + line + code

            if "startFragment(ContactInfoFragment.create(), true);" in line:
                code = "\n\t\t\t\tnew EventSender.Builder(MessageID.CERTIFY_PROGRESS_CHANGED).obj(ContactInfoFragment.create()).build().sendEvent();\n"
                line = "// " + line + code

            if "startFragment(ProfessionalFragment.create(), true);" in line:
                code = "\n\t\t\t\tnew EventSender.Builder(MessageID.CERTIFY_PROGRESS_CHANGED).obj(ProfessionalFragment.create()).build().sendEvent();"
                line = "// " + line + code

            if "startFragment(AccountFragment.create(), true);" in line:
                code = "\n\t\t\t\t\tnew EventSender.Builder(MessageID.CERTIFY_PROGRESS_CHANGED).obj(AccountFragment.create()).build().sendEvent();\n"
                line = "// " + line + code

            f_w.write(line)
    print ("code_fragments updated !")
    return


def code_certifyprogress(path):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        # readlines以列表的形式将文件读出
        lines = f.readlines()

    with open(path, "w", encoding="utf-8") as f_w:
        flag = False
        for line in lines:
            #1
            if "public static void start(FragmentActivity context, CertifyType certifyType) {" in line:
                flag = True
            if flag and "}" in line:
                flag = False
                code = "\n\tpublic static void start(FragmentActivity context, CertifyType certifyType, ProductBean productBean) {\n" + \
                       "\t\tnew ActivityJumper.Builder(context, CertifyProgressActivity.class).put(\"certigy_type\", certifyType).put(\"productBean\", productBean).build().start();\n" + \
                       "\t}\n"
                code += "\n\n"
                code += "\t@Subscribe\n" + \
                        "\tpublic void onEvent(EventMessage msg) {\n" + \
                        "\t\tif (msg.what == MessageID.CERTIFY_PROGRESS_CHANGED) {\n" +\
                        "\t\t\tFragment fragment = (Fragment) msg.obj;\n" + \
                        "\t\t\tBundle arguments = fragment.getArguments();\n" + \
                        "\t\t\tif (arguments != null) {" + \
                        "\t\t\t\targuments.putAll(getIntent().getExtras());\n" + \
                        "\t\t\t}else{\n" + \
                        "\t\t\t\targuments= getIntent().getExtras();\n" + \
                        "\t\t\t}\n" + \
                        "\t\tfragment.setArguments(arguments);\n"+\
                        "\t\tstartFragment(fragment, true);\n" + \
                        "\t\t}\n" + \
                        "\t}\n\n"
                line = line + code

            #2
            if "startFragment(AccountFragment.create(), false);" in line :
                code = "\n\t\t\t\tAccountFragment accountFragment = AccountFragment.create();\n" + \
                       "\t\t\t\taccountFragment.setArguments(getIntent().getExtras());\n" + \
                       "\t\t\t\tstartFragment(accountFragment, false);\n"
                line = line + code


        f_w.write(line)
    print ("code_fragments updated !")
    return


for root, dirs, files in os.walk("../../app/src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        if file.endswith("LoanApplyFragment.java"):
            # get the path of the java file
            path = os.path.join(directory, file)
            code_loanapplyfragment(path)
        elif file.endswith("CertifyActivity.java"):
            path = os.path.join(directory, file)
            code_certifyactivity(path)
        elif file.endswith("IdentityInfoFragment.java") or file.endswith(
                "PersonalInfoFragment.java") or file.endswith(
                "ContactInfoFragment.java") or file.endswith("ProfessionalFragment.java")
            path = os.path.join(directory, file)
            code_fragments(path)
        elif file.endswith("CertifyProgressActivity.java"):
            path = os.path.join(directory, file)
            code_certifyprogress(path)
