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

def rename_api(path):
    with open("../../../script/api_mapping", "r", encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            #去除无用字符
            api_map = line.replace("rewrite ^/","").replace("/(.+)","").replace("$ /","*-*").replace(" last;","").replace("\n","") \
                .replace("/$1","").replace("/$2","").replace("/$3","").replace("/$4","").replace("/$5","") \
                .split("*-*")
            # print(api_map[1]+ " -> " + api_map[0])

            with open(path, "r", encoding="utf-8") as api_file:
                api_lines = api_file.readlines()
            #替换api
            with open(path, "w", encoding="utf-8") as f_w:
                for api_l in api_lines:
                    if "//API-REPAIR*-*" in api_l:
                        api_l = "\t"+api_l.split("*-*")[1]

                    if (api_map[1]+"/" in api_l or api_map[1]+"\"" in api_l) and ( "@GET" in api_l or "@PUT" in api_l or "@POST" in api_l):
                        api_l = api_l.replace(api_map[1], api_map[0])
                        print(api_map[1]+ " -> " + api_map[0])
                    f_w.write(api_l)
    print(path + "  done\n")
    return


#java目录的路径
for root, dirs, files in os.walk("../../src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        #要检索的文件名
        if file.endswith("LoanApi.java") or file.endswith("UploadApi.java") or file.endswith("UserApi.java"):
            # get the path of the java file
            path = os.path.join(directory, file)
            rename_api(path)