package com.sagacloud.utils;
/*
 * Author: Jxing
 * Create Time: 2018/10/12
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.sagacloud.utils.tables.HBaseTable;
import com.sagacloud.utils.tables.ObjectTable;

import java.util.HashSet;
import java.util.Set;

public class SpaceUtils {
    /**
     * 获取因为元空间变化导致业务空间受影响的的idSet
     * @param pjId 不带Pj的项目号
     * @return 业务空间的id集合
     */
    public static Set<String> getAffectedSpaceIdList(String pjId) {
        JSONObject criteria = new JSONObject();
        criteria.put(ObjectTable.KEY_PJ_ID, pjId);
        criteria.put(ObjectTable.KEY_OBJ_TYPE, Const.OBJ_TYPE_SPACE);
        JSONArray arr = new JSONArray();
        arr.add(criteria);
        try {
            Set<String> idSet = new HashSet<>();
            JSONObject result = CommonUtil.combine_query(HBaseTable.business_space_notice, arr);
            JSONArray content = result.getJSONArray(Const.JSON_FIELD_Content);
            for(int i = 0; i < content.size(); ++i){
                JSONObject obj = content.getJSONObject(i);
                String id = CommonUtil.combineId(pjId, Const.OBJ_TYPE_SPACE, Strings.nullToEmpty((String) obj.get(ObjectTable.KEY_OBJ_ID)));
                if(!idSet.contains(id)){
                    idSet.add(id);
                }
            }
            return idSet;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashSet<>();
        }
    }

    /**
     * 删除指定的业务空间通知(受影响的业务空间)
     * @param pjId 不带Pj的项目id
     * @param idSet 要删除的业务空间id
     * @throws Exception 数据库异常
     */
    public static void deleteAffectedSpaceIds(String pjId, Set<String> idSet) throws Exception {
        JSONArray arr = new JSONArray();
        for(String id : idSet){
            JSONObject obj = new JSONObject();
            obj.put("id", id);
            try {
                CommonUtil.rewriteObjectTableCriteria(pjId, obj, "id", true);
                arr.add(obj);
            } catch (Exception e) {
            }
        }
        CommonUtil.combine_delete(HBaseTable.business_space_notice, arr);
    }
}
