package com.kingdee.eas.custom.integration.weaver.config;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 泛微 E10 OAuth2 接口地址配置，对应 integration-config.json 的 weaver 节点。
 */
public class WeaverConfig {

    private static final String DEFAULT_AUTHORIZE_PATH = "/papi/sso/oauth2.0/authorize";
    private static final String DEFAULT_ACCESS_TOKEN_PATH = "/papi/sso/oauth2.0/accessToken";
    private static final String DEFAULT_PROFILE_PATH = "/papi/sso/oauth2.0/profile";
    private static final String DEFAULT_LOGOUT_PATH = "/sp/integration/oauth2.0/logout";

    private String ecologyUrl;
    private String authorizePath = DEFAULT_AUTHORIZE_PATH;
    private String accessTokenPath = DEFAULT_ACCESS_TOKEN_PATH;
    private String profilePath = DEFAULT_PROFILE_PATH;
    private String logoutPath = DEFAULT_LOGOUT_PATH;

    public WeaverConfig() {
    }

    public WeaverConfig(Map<String, String> weaver) {
        if (weaver == null) {
            return;
        }
        this.ecologyUrl = trimTrailingSlash(weaver.get("ecologyUrl"));
        this.authorizePath = defaultPath(weaver.get("authorizePath"), DEFAULT_AUTHORIZE_PATH);
        this.accessTokenPath = defaultPath(weaver.get("accessTokenPath"), DEFAULT_ACCESS_TOKEN_PATH);
        this.profilePath = defaultPath(weaver.get("profilePath"), DEFAULT_PROFILE_PATH);
        this.logoutPath = defaultPath(weaver.get("logoutPath"), DEFAULT_LOGOUT_PATH);
    }

    public String getAuthorizeUrl() {
        return ecologyUrl + authorizePath;
    }

    public String getAccessTokenUrl() {
        return ecologyUrl + accessTokenPath;
    }

    public String getProfileUrl() {
        return ecologyUrl + profilePath;
    }

    public String getLogoutUrl() {
        return ecologyUrl + logoutPath;
    }

    public boolean isConfigured() {
        return StringUtils.isNotBlank(ecologyUrl);
    }

    private static String defaultPath(String value, String defaultValue) {
        return StringUtils.isBlank(value) ? defaultValue : value;
    }

    private static String trimTrailingSlash(String url) {
        if (url == null) {
            return null;
        }
        while (url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

    @Override
    public String toString() {
        return "WeaverConfig{ecologyUrl='" + ecologyUrl + "'}";
    }
}
