package com.sagacloud.cache;

import com.google.common.base.Strings;
//import com.sagacloud.json.JSONArray;
//import com.sagacloud.json.JSONObject;
import com.alibaba.fastjson.*;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Hashtable;

/**
 * Created by wo on 4/26/17.
 */
public class ProPasCache {
    public static Hashtable<String, byte[]> proPass = new Hashtable<>();

    private static final Logger log = LoggerFactory.getLogger(ProPasCache.class);



    public static String get(String key){
        if(proPass.get(key) == null){
            return  null;
        }
        return new String(proPass.get(key));
    }
    public static boolean Contains(String key){
        if(proPass.containsKey(key)){
            return  true;
        }
        return false;
    }

    public static void synCache(){
        log.info("start to syn proPasCache.");
        Hashtable<String, byte[]> tempProPass = new Hashtable<>();
        //String reStr = CommonMethods.query(Const.TABLE_PROJECT_NAME, "", "{\"criteria\":{}}", false);
        JSONArray arr = ObjectUtil.getProjectPwd();
        if(arr == null || arr.size() == 0){
            log.warn("Succeeded to syn proPasCache, but result is empty.");
            return;
        }
        for(int i = 0; i < arr.size(); i++){
            JSONObject proNode = (JSONObject)arr.get(i);
            tempProPass.put(Const.OBJ_TYPE_PROJECT + proNode.get("project_id").toString(), Strings.nullToEmpty((String)proNode.get("password")).getBytes());
        }
        if(tempProPass.size() > 0){
            log.info("Succeeded to syn proPasCache.");
            proPass = tempProPass;
        }
    }
}
