package jp.agentec.abook.abv.bl.acms.client.json;

import java.util.ArrayList;
import java.util.Arrays;

import jp.agentec.abook.abv.bl.acms.client.AcmsClient;
import jp.agentec.abook.abv.bl.common.exception.AcmsException;
import jp.agentec.abook.abv.bl.common.exception.JSONValidationException;
import jp.agentec.abook.abv.bl.dto.GroupDto;

import org.json.adf.JSONArray;
import org.json.adf.JSONObject;

/**
 * {@link AcmsClient#group} の戻り値です。
 * @author Taejin Hong
 * @version 1.0.0 
 */
public class GroupsJSON extends AcmsCommonJSON {
	public static final String GroupList = "groupList";
	public static final String GroupId = "groupId";
	public static final String GroupName = "groupName";
	public static final String GroupLevel = "groupLevel";
	public static final String ParentGroupId = "parentGroupId";
	public static final String UserGroupIds = "userGroupIds";
	public static final String GroupCode = "groupCode";
	
	public ArrayList<GroupDto> groupList;
	public Integer[] userGroupIds;
	
	public GroupsJSON(String jsonString) throws AcmsException {
		super(jsonString);
	}
	
	@Override
	protected void parse(JSONObject json) throws JSONValidationException {
		if (json.has(GroupList)) {
			JSONArray jarr = json.getJSONArray(GroupList);
			
			int count = jarr.length();
			groupList = new ArrayList<GroupDto>();
			
			// 所属グループ
			JSONArray userGroupIdsArray = json.getJSONArray(UserGroupIds);
			if (userGroupIdsArray != null && userGroupIdsArray.length() > 0) {
				int userGroupIdsCount = userGroupIdsArray.length();
				userGroupIds = new Integer[userGroupIdsCount];
				for (int i = 0; i < userGroupIdsCount; i++) {
					userGroupIds[i] = userGroupIdsArray.getInt(i);
				}
				Arrays.sort(userGroupIds);
			}
			
			for (int i = 0; i < count; i++) {
				JSONObject group = jarr.getJSONObject(i);
				int groupId = getInt(group, GroupId);
				String groupName = getString(group, GroupName);
				short groupLevel = (short) getInt(group, GroupLevel);
				int parentGroupId = getInt(group, ParentGroupId);
				String groupCode = "";
				if (group.has(GroupCode)) {
					groupCode = getString(group, GroupCode);
				}

				// ユーザが所属しているグループフラグ
				boolean userGroupFlg = false;
				if (userGroupIds != null) {
					userGroupFlg = Arrays.asList(userGroupIds).contains(groupId);
				}

				groupList.add(new GroupDto(groupId, groupName, groupLevel,parentGroupId, userGroupFlg, groupCode));
			}
		} else {
			throw new JSONValidationException(json.toString(), GroupList + " property not found.");
		}
	}
}
