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

def rename_api(path):
    # print("processing content: %s..." % path)
    with open(path, "rt") as fin:
        #Api源码
        file_content = fin.read()

        with open("api_mapping", "r", encoding="utf-8") as f:
            lines = f.readlines()
            for line in lines:
                # rewrite ^/aaaag/aahlav$ /loanapp/all/v2 last;
                api_map = line.replace("\n","").replace("rewrite ^/","").replace("/(.+)","").replace("$ /","*_*").replace(" last;","")\
                    .replace("/$1","").replace("/$2","").replace("/$3","").replace("/$4","").replace("/$5","")\
                    .split("*_*")

                # print(api_map[1]+ " -> " + api_map[0])
                if "@GET" in line or "@PUT" in line or "@POST" in line:
                    file_content.replace(api_map[1], api_map[0])

        with open(path, "wt") as fout:
            fout.write(file_content)
        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)