package com.sagacloud.dict;

import com.sagacloud.json.JSONArray;
import com.sagacloud.json.JSONObject;
import com.sagacloud.json.JSONValue;
import com.sagacloud.utils.OssUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Hashtable;

public class TableMap {
    private static final Logger log = LoggerFactory.getLogger(TableMap.class);
    private static Hashtable<String, String> InfoToTableNameMap;
    private static Hashtable<String, String> InfoToNamespaceMap;
    private static void init() {
        InfoToTableNameMap = new Hashtable<>();//type+","+code-->tableName
        InfoToNamespaceMap = new Hashtable<>();//type+","+code-->namespace
        try {
            String jsonStr = OssUtils.getFileAsString("Config/TableMap.json");
            JSONArray all = (JSONArray) ((JSONObject) JSONValue.parse(jsonStr)).get("all");
            for(int i = 0; i < all.size(); ++i){
                JSONObject outterObj = (JSONObject) all.get(i);
                String namespace = outterObj.get("namespace").toString();
                for(int j = 0; j < ((JSONArray) outterObj.get("content")).size(); ++j){
                    JSONObject midObj = (JSONObject) ((JSONArray) outterObj.get("content")).get(j);
                    String tableName = midObj.get("tableName").toString();
                    for(int k = 0; k < ((JSONArray) midObj.get("content")).size(); ++k){
                        JSONObject innerObj = (JSONObject) ((JSONArray) midObj.get("content")).get(k);
                        String type = innerObj.get("type").toString();
                        String code = innerObj.get("code").toString();
                        InfoToNamespaceMap.put(type+","+code,namespace);
                        InfoToTableNameMap.put(type+","+code,tableName);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(Arrays.toString(e.getStackTrace()));
        }
    }

    public static String getNamespace(String type,String code){
        if(InfoToNamespaceMap == null || InfoToNamespaceMap.size() == 0)
            init();
        return InfoToNamespaceMap.get(type+","+code);
    }

    public static String getTableName(String type,String code){
        if(InfoToTableNameMap == null || InfoToTableNameMap.size() == 0)
            init();
        return InfoToTableNameMap.get(type+","+code);
    }

    public static void clearCache(){
        if(InfoToNamespaceMap!=null)
            InfoToNamespaceMap.clear();
        if(InfoToTableNameMap!=null)
            InfoToTableNameMap.clear();
    }
}
