package com.malk.service.eiam.impl;

import com.alibaba.fastjson.JSON;
import com.malk.server.eiam.EiamConf;
import com.malk.server.eiam.EiamOrganizationalUnitPage;
import com.malk.service.eiam.EiamClient_OrganizationalUnit;
import com.malk.utils.UtilHttp;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * EIAM DeveloperAPI 组织管理原子接口实现。
 */
@Service
public class EiamClient_OrganizationalUnitImpl implements EiamClient_OrganizationalUnit {

    private final EiamConf eiamConf;

    public EiamClient_OrganizationalUnitImpl(EiamConf eiamConf) {
        this.eiamConf = eiamConf;
    }

    @Override
    public EiamOrganizationalUnitPage listOrganizationalUnits(String accessToken,
                                                              String instanceId,
                                                              String applicationId,
                                                              String parentId,
                                                              Integer pageNumber,
                                                              Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", parentId);
        params.put("pageNumber", pageNumber);
        params.put("pageSize", pageSize);
        String response = UtilHttp.doGet(usersBaseUrl(instanceId, applicationId),
                headers(accessToken), params);
        return JSON.parseObject(response, EiamOrganizationalUnitPage.class);
    }

    private String usersBaseUrl(String instanceId, String applicationId) {
        return eiamConf.getBaseUrl() + "/v2/" + instanceId + "/" + applicationId
                + "/organizationalUnits";
    }

    private Map<String, String> headers(String accessToken) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + accessToken);
        return headers;
    }
}
