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.InputStream;
import java.util.*;

public class RelStaticInfo {
    final static String globalRelationPath = "property/Dictionary/GlobalRelation.json";
    private static final Logger log = LoggerFactory.getLogger(RelStaticInfo.class);
    //key : graph_type+","+rel_type, value 判断是否有向 ture 有向, false 无向
    public static Map<String, Boolean> globalGraphRelMap = new HashMap<>();
    //key : graph_type, value 图类型下的所有关系类型集合.
    public static Map<String, Set<String>> globalGraphRelSetMap = new HashMap<>();
    //存储全局graph_type
    public static Set<String> globalGraphSet = new HashSet<>();
    //包含字段{graph_type,graph_name,rel_type,rel_name,directional,description}
    public static JSONArray globalDefArray = new JSONArray();

    static{
        init();
    }

    public static void init(){
        try{
            String jsonStr = OssUtils.getFileAsString(globalRelationPath);
            JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
            JSONArray all = (JSONArray) json.get("all");
            for(int i = 0; i < all.size(); ++i){
                JSONObject item = (JSONObject) all.get(i);
                String graph_type = (String) item.get("graph_type");
                String graph_name = (String) item.get("graph_name");
                globalGraphSet.add(graph_type);
                if(!globalGraphRelSetMap.containsKey(graph_type)){
                    globalGraphRelSetMap.put(graph_type, new HashSet<>());
                }
                JSONArray content = (JSONArray) item.get("Content");
                for(int j = 0; j < content.size(); ++j){
                    JSONObject relItem = (JSONObject) content.get(j);
                    String rel_type = (String) relItem.get("rel_type");
                    boolean directional = (Boolean) ((JSONObject) content.get(j)).get("directional");
                    globalGraphRelMap.put(String.join(",",graph_type,rel_type),directional);
                    relItem.put("graph_type",graph_type);
                    relItem.put("graph_name",graph_name);
                    globalDefArray.add(relItem);
                    if(globalGraphRelSetMap.containsKey(graph_type)){
                        Set<String> relSet = globalGraphRelSetMap.get(graph_type);
                        if(!relSet.contains(rel_type)){
                            relSet.add(rel_type);
                        }
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error(Arrays.toString(e.getStackTrace()));
        }
    }

}
