/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.webutilities

import org.apache.http.impl.client.CloseableHttpClient

import com.urbancode.commons.httpcomponentsutil.CloseableHttpClientBuilder


/**
 * A method that builds an apache httpclient using our internal library
 *
 * @param   password                        Password String for authentication
 * @param   preemptiveAuthentication        Boolean true if client should do preemptive authentication.
 * @param   proxyHost                       A String represtsing the proxy host name
 * @param   proxyPassword                   A String password for the proxy authentication
 * @param   proxyPort                       A String Integer
 * @param   proxyUsername                   A String username
 * @param   trustAllCerts                   Boolean true if all certifactes should be trusted
 * @param   username                        String username for endpoint
 * @return                                  An apache http components closable httpclient
 */
public static CloseableHttpClient buildHTTPClient (
    String password = "",
    boolean preemptiveAuthentication = false,
    String proxyHost = "", String proxyPassword = "",
    String proxyPort = "",
    String proxyUsername = "",
    boolean trustAllCerts = true,
    String username = "") {
    try {
        CloseableHttpClientBuilder clientBuilder = new CloseableHttpClientBuilder()
        clientBuilder.setTrustAllCerts(trustAllCerts)
        if (username && password) {
            clientBuilder.setUsername(username)
            clientBuilder.setPassword(password)
            clientBuilder.setPreemptiveAuthentication(preemptiveAuthentication)
        }
        if (proxyHost) {
            clientBuilder.setProxyHost(proxyHost)
            clientBuilder.setProxyPassword(proxyPassword)
            if(proxyPort) {
                clientBuilder.setProxyPort(Integer.valueOf(proxyPort))
            }
            if(proxyUsername) {
                clientBuilder.setProxyUsername(proxyUsername)
            }
        }
        return clientBuilder.buildClient()
    } catch (Exception e) {
        throw e
    }
}
