package com.sagacloud.endpoints.customDict;

import java.util.Arrays;

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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.utils.CommonUtil;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.tables.HBaseTable;

@Path("custom_dict")
public class CtmDictFollower {

	private static final Logger log = LoggerFactory.getLogger(CtmDictFollower.class);
	
	@Path("/dict_follower/create")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String createFollower(String jsonStr) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		String dictId = (String) json.get("dict_id");
		String projectId = (String) json.get("project_id");
    	if(StringUtils.isBlank(dictId)) {
    		return DpUtils.errorJsonMsg("missing key : dict_id");
    	}
    	if(StringUtils.isBlank(projectId)) {
    		return DpUtils.errorJsonMsg("missing key : project_id");
    	}
    	if(!projectId.startsWith("Pj")) {
    		return DpUtils.errorJsonMsg("project_id must start with Pj");
    	}
    	projectId = projectId.replace("Pj", "");
    	JSONObject criteria = new JSONObject();
    	JSONObject re = null;
		try {
			
			criteria.put("project_id", projectId);
			re = CommonUtil.query(false, HBaseTable.projects, criteria);
			if (re.get("Result").toString().equals("success")) {
				Number count = (Number) re.get("Count");
				if(count.intValue() <= 0) {
					return DpUtils.errorJsonMsg("无此项目id：" + projectId);
				}
			}else {
				return re.toString();
			}
			
			criteria.clear();
			criteria.put("id", dictId);
			re = CommonUtil.query(false, HBaseTable.ctm_dict, criteria);
			if (re.get("Result").toString().equals("success")) {
				Number count = (Number) re.get("Count");
				if(count.intValue() <= 0) {
					return DpUtils.errorJsonMsg("无此数据字典方案id：" + dictId);
				}
			}else {
				return re.toString();
			}
			
			criteria.clear();
			/*criteria.put("project_id", projectId);
			re = CommonUtil.query(false, HBaseTable.ctm_dict_follower, criteria);
			if (re.get("Result").toString().equals("success")) {
				Number count = (Number) re.get("Count");
				if(count.intValue() > 0) {
					 return DpUtils.errorJsonMsg("一个项目只能使用一套方案");
				}
			}else {
				return re.toString();
			}*/
			criteria.put("project_id", "Pj" + projectId);
			this.deleteFollower(criteria.toString());
			
			json.put("project_id", projectId);
			re = CommonUtil.insert(false, HBaseTable.ctm_dict_follower, json);
			MessageHandler.publish(String.format("{\"type\":13,\"projectId\":\"%s\",\"description\":\"\"}",projectId));
			return re.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}

	}
	
	@Path("/dict_follower/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String queryFollower(String jsonStr) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		String projectId = (String) json.get("project_id");
    	if(StringUtils.isBlank(projectId)) {
    		return DpUtils.errorJsonMsg("missing key : project_id");
    	}
    	
    	if(!projectId.startsWith("Pj")) {
    		return DpUtils.errorJsonMsg("project_id must start with Pj");
    	}
    	projectId = projectId.replace("Pj", "");
    	
		JSONObject criteria = new JSONObject();
    	JSONObject re = null;

		try {
			
			criteria.put("project_id", projectId);
			re = CommonUtil.query(false, HBaseTable.projects, criteria);
			if (re.get("Result").toString().equals("success")) {
				Number count = (Number) re.get("Count");
				if(count.intValue() <= 0) {
					return DpUtils.errorJsonMsg("无此项目id：" + projectId);
				}
			}else {
				return re.toString();
			}
			
			criteria.clear();
			criteria.put("project_id", projectId);
			re = CommonUtil.query(false, HBaseTable.ctm_dict_follower, criteria);
			if (re.get("Result").toString().equals("success")) {
				criteria.clear();
				Number count = (Number) re.get("Count");
				if(count.intValue() > 0) {
					JSONArray content = (JSONArray) re.get("Content");
					JSONObject obj = (JSONObject) content.get(0);
					criteria.put("id", obj.get("dict_id"));
				}else {
					criteria.put("id", "none");
				}
				re = CommonUtil.query(false, HBaseTable.ctm_dict, criteria);
				return re.toString();
			}else {
				return re.toString();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}
	}
	
	@Path("/dict_follower/delete")
	@POST
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteFollower(String jsonStr) {
		
		JSONObject json = JSONObject.parseObject(jsonStr);
		String projectId = (String) json.get("project_id");
    	if(StringUtils.isBlank(projectId)) {
    		return DpUtils.errorJsonMsg("missing key : project_id");
    	}
    	
    	if(!projectId.startsWith("Pj")) {
    		return DpUtils.errorJsonMsg("project_id must start with Pj");
    	}
    	projectId = projectId.replace("Pj", "");
    	
		JSONObject criteria = new JSONObject();
    	JSONObject re = null;

		try {
			
			criteria.put("project_id", projectId);
			re = CommonUtil.query(false, HBaseTable.projects, criteria);
			if (re.get("Result").toString().equals("success")) {
				Number count = (Number) re.get("Count");
				if(count.intValue() <= 0) {
					return DpUtils.errorJsonMsg("无此项目id：" + projectId);
				}
			}else {
				return re.toString();
			}
			
			criteria.clear();
			criteria.put("project_id", projectId);
			re = CommonUtil.delete(false, HBaseTable.ctm_dict_follower, criteria);
			MessageHandler.publish(String.format("{\"type\":13,\"projectId\":\"%s\",\"description\":\"\"}",projectId));
			return re.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("", e);
            return DpUtils.errorJsonMsg(Arrays.toString(e.getStackTrace()));
		}
	}
}
