package com.avaya.customer.example.servlet.utils;

import com.avaya.collaboration.authorization.AccessToken;
import com.avaya.collaboration.authorization.AuthorizationClientHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Authorization {

    private static final Logger LOG = LoggerFactory.getLogger(Authorization.class);

    static AccessToken getAccessToken(Configuration configuration) throws Exception {

        final String authorizationUrl = Utils.buildHttpSecureUrl(configuration.getAuthorizationHost() + ":"
                + configuration.getAuthPort(), "/services/AuthorizationService/token");

        AuthorizationClientHelper authorizationClientHelper = null;
        try {
            LOG.info("Getting access token from {} ...", authorizationUrl);
            authorizationClientHelper = new AuthorizationClientHelper.Builder()
                    .tokenEndpoint(authorizationUrl)
                    .clientIdentifier(configuration.getClientId())
                    .keyStore(configuration.getClientKeyStore(), configuration.getKeyStorePassword(), configuration.getKeyAlias())
                    .trustStore(configuration.getClientTrustStore())
                    .build();

            AccessToken accessToken = authorizationClientHelper.getAccessToken();
            LOG.info("Token received");

            return accessToken;
        } catch (Exception e) {
            LOG.error("Exception thrown during getting access token: ", e);
        } finally {
            if (authorizationClientHelper != null) {
                authorizationClientHelper.shutdown();
            }
        }
        return null;
    }

    private Authorization() {}
}
