/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
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
    }
}
