package com.sagacloud.endpoints.mng;

import com.alibaba.fastjson.*;
import com.sagacloud.utils.*;
import com.sagacloud.utils.objectLog.ActivityLogUtil;
import com.sagacloud.utils.objects.MQType;
import com.sagacloud.utils.objects.ObjectIdName;
import com.sagacloud.utils.objects.ObjectType;
import com.sagacloud.utils.relationUtils.SubsetUtil;
import com.sagacloud.utils.tables.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Set;

/**
 * Created by wushengzong on 2017/4/24.
 */
@Path("mng/building")
public class Building {
    private static final Logger log = LoggerFactory.getLogger(Building.class);
    @Path("/create")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String create(String jsonStr){
        try {
            JSONObject insertJson = JSONObject.parseObject(jsonStr);
            if(!(insertJson.containsKey(BuildingTable.KEY_PJ_ID) || insertJson.containsKey(Const.PROJECT_ID) || insertJson.containsKey("id"))|| !insertJson.containsKey(Const.JSON_FIELD_JSON_DATA_INFOS)){
                return DpUtils.errorJsonMsg("缺少必要字段");
            }
            String project_id = "";
            String assignedObjId = null;
            if(insertJson.get("id")!= null)
            {
                // 指定id创建对象
                if(insertJson.get("id").toString().startsWith("Bd")) {
                    String assignedId = insertJson.get("id").toString();
                    project_id = assignedId.substring(0, 12);
                    assignedObjId = assignedId.substring(12);
                    if (!DpUtils.verifyAssignedObjID(assignedObjId)) {
                        return DpUtils.errorJsonMsg("指定的id错误.");
                    }
                }else
                    throw new Exception("指定的id错误");
            }else {
                // 自动产生id
                project_id = insertJson.getString(BuildingTable.KEY_PJ_ID);
                if(StringUtils.isBlank(project_id)){
                    project_id = insertJson.getString(Const.PROJECT_ID);
                }

            }
            JSONObject project_valid_criteria = new JSONObject();
            project_valid_criteria.put(ProjectTable.KEY_PJ_ID, project_id.substring(2));
            project_valid_criteria.put(Const.TABLE_KEY_NAME_VALID, true);
            JSONObject project_valid = CommonUtil.query(false, HBaseTable.projects, project_valid_criteria);
            if(project_valid.get("Count").equals(0L))
            {
                return DpUtils.errorJsonMsg("该项目Id不存在或已被删除");
            }
            //((JSONObject) insertJson.get(Const.JSON_FIELD_JSON_DATA_INFOS)).put(Const.JSON_FIELD_CTEATE_TIME, CommonUtil.getTime());
            ObjectIdName name = new ObjectIdName();
            String id = ObjectUtil.addObj(project_id.substring(2), Const.OBJ_TYPE_BUILDING,"",
                    (JSONObject) insertJson.get(Const.JSON_FIELD_JSON_DATA_INFOS), ObjectType.building, name, assignedObjId, true);
            return DpUtils.successJsonMsgWithId("", id, name.getNameKey(), name.getNameValue());
        }catch (Exception ex)
        {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(ex.getMessage() == null? "添加失败!": ex.getMessage());
        }
    }


    @Path("/delete")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String delete(String jsonStr){
        try
        {
            JSONObject criteria = JSONObject.parseObject(jsonStr);
            criteria = (JSONObject) criteria.get("criteria");
            if(criteria.get("id") == null || !criteria.get("id").toString().startsWith(Const.OBJ_TYPE_BUILDING))
                throw new Exception("id错误!");

            // check if all facility, system and floor belong to this building all been deleted
            String id = criteria.get("id").toString();
            Set<String> typeSet = SubsetUtil.findChildrenType(id.substring(2, 12), id);

            if(typeSet.size() != 0)
                throw new Exception(CommonUtil.getErrorMsg(typeSet, "请先删除建筑下面的"));

            // delete all relation with this building.
//            JSONArray relationArray = new JSONArray();
//            JSONObject from_relation = new JSONObject();
//            from_relation.put("from_id", criteria.get("id").toString());
//            JSONObject to_relation = new JSONObject();
//            to_relation.put("to_id", criteria.get("id").toString());
//            relationArray.add(from_relation);
//            relationArray.add(to_relation);
//            JSONObject obj = new JSONObject();
//            obj.put("criterias", relationArray);
//            RelationUtil.deleteRelation(criteria.get("id").toString().substring(2), obj);
//            log.info("已删除建筑体" + criteria.get("id").toString() + "的所有关系.");
            //
            // set building to false
            JSONObject updateCriteria = new JSONObject();
            JSONObject set = new JSONObject();
            updateCriteria.put(ObjInfosTable.KEY_PJ_ID, criteria.get("id").toString().substring(2, 12));
            updateCriteria.put(ObjInfosTable.KEY_OBJ_TYPE, criteria.get("id").toString().substring(0, 2));
            updateCriteria.put(ObjInfosTable.KEY_OBJ_ID, criteria.get("id").toString().substring(12));
            String time = CommonUtil.getTime();
            set.put(ObjectTable.KEY_DEL_TIME, time);
            set.put(Const.TABLE_KEY_NAME_VALID, false);
            JSONObject result = CommonUtil.update(false, HBaseTable.objects, updateCriteria, set);
            if(result.get("Count").equals(0))  // 如果更新失败, 则不往下进行删除信息点
                return DpUtils.errorJsonMsg("删除失败或者没有数据.");
            // 信息点不变
            //CommonUtil.deleteInfoPointToHistory(criteria.get("id").toString().substring(2,12), Const.OBJ_TYPE_BUILDING, criteria.get("id").toString().substring(12));
//            ActivityLogUtil.objectLog(criteria.get("id").toString(), time, "建筑删除", MQType.objectDelete);
            ActivityLogUtil.objectLog(criteria.get("id").toString(), time, "作废一个对象实例", MQType.objectDelete);
            return DpUtils.successJsonMsg("");
        }catch (Exception ex)
        {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(ex.getMessage());
        }
    }
}
