package com.sagacloud.endpoints.customDict;

import java.util.*;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.sagacloud.broadcast.MessageHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.sagacloud.utils.CommonUtil;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.tables.CtmDictTable;
import com.sagacloud.utils.tables.HBaseTable;

/**
 * Created by wo on 7/18/19.
 */
@Path("custom_dict")
public class CtmDict {
    private static final Logger log = LoggerFactory.getLogger(CtmDict.class);
    @Path("/dict/create")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String createScheme(String jsonStr) {
        JSONObject json = JSONObject.parseObject(jsonStr);
        if (json.get(CtmDictTable.COL_NAME) == null) {
            return DpUtils.errorJsonMsg("missing key : " + CtmDictTable.COL_NAME);
        }
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString().replace("-", "");
        json.put(CtmDictTable.KEY_ID, id);
        try {
            JSONObject re = CommonUtil.insert(false, HBaseTable.ctm_dict, json);
            if (re.get("Result").toString().equals("success")) {
                re = JSONObject.parseObject(DpUtils.successJsonMsg(""));
                re.put(CtmDictTable.KEY_ID, id);
                return re.toString();
            }
            return DpUtils.errorJsonMsg("已存在");
        } catch (Exception e) {
            log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
        }
    }

    /**根据id验证字典是否存在
     * @param id
     * @return
     */
    public boolean isExisted(String id) throws Exception {
        if(id == null){
            return false;
        }
        JSONObject cri = new JSONObject().fluentPut(CtmDictTable.KEY_ID, id);
        if(CommonUtil.query(false, HBaseTable.ctm_dict, cri).getJSONArray("Content").size() > 0){
            return true;
        }
        return false;
    }
    
    @Path("/dict/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryScheme(String jsonStr) {
    	JSONObject json = JSONObject.parseObject(jsonStr);
    	JSONObject criteria = (JSONObject) json.get("criteria");
    	if(criteria==null) {
    		criteria = new JSONObject();
    	}
    	try {
            JSONObject followerRe = CommonUtil.query(false, HBaseTable.ctm_dict_follower, new JSONObject());
            Map<String, List<String>> dictToPjs = new HashMap<>();
            followerRe.getJSONArray("Content").forEach(o -> {
                JSONObject item = (JSONObject) o;
                String dictId = item.getString("dict_id");
                String pjId = item.getString("project_id");
                if(dictToPjs.get(dictId) == null){
                    dictToPjs.put(dictId, new ArrayList<>());
                }
                dictToPjs.get(dictId).add("Pj" + pjId);
            });
    		JSONObject re = CommonUtil.query(false, HBaseTable.ctm_dict, criteria);
            re.getJSONArray("Content").forEach(o -> {
                JSONObject item = (JSONObject) o;
                item.put("follower", dictToPjs.get(item.getString(CtmDictTable.KEY_ID)));
            });
    		return re.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}
    }
    
    @Path("/dict/update")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String updateScheme(String jsonStr) {
    	JSONObject json = JSONObject.parseObject(jsonStr);
    	JSONObject criteria = (JSONObject) json.get("criteria");
    	if(criteria==null) {
    		return DpUtils.errorJsonMsg("missing key : criteria");
    	}
    	JSONObject set = (JSONObject) json.get("set");
    	if(set==null) {
    		return DpUtils.errorJsonMsg("missing key : set");
    	}
    	String id = (String) criteria.get("id");
    	if(StringUtils.isBlank(id)) {
    		return DpUtils.errorJsonMsg("missing key : id");
    	}
    	
    	String name = (String) set.get("name");
    	String desc = (String) set.get("desc");
    	if(StringUtils.isBlank(name) && StringUtils.isBlank(desc)) {
    		return DpUtils.errorJsonMsg("missing key : name or desc");
    	}
    	
    	try {
    		JSONObject re = CommonUtil.update(false, HBaseTable.ctm_dict, criteria, set);
			return re.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}

    }
    
    @Path("/dict/delete")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteScheme(String jsonStr) {
    	JSONObject json = JSONObject.parseObject(jsonStr);
    	JSONObject criteria = (JSONObject) json.get("criteria");
    	if(criteria==null) {
    		return DpUtils.errorJsonMsg("missing key : criteria");
    	}
    	String id = (String) criteria.get("id");
    	if(StringUtils.isBlank(id)) {
    		return DpUtils.errorJsonMsg("missing key : id");
    	}
    	try {
    		JSONObject re = CommonUtil.delete(false, HBaseTable.ctm_dict, criteria);
            MessageHandler.publish(String.format("{\"type\":12,\"projectId\":\"\",\"dictId\":\"%s\",\"description\":\"\"}",id));
    		return re.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}
    }
}
