/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * IBM AnthillPro
 * (c) Copyright IBM Corporation 2014. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
import java.nio.charset.Charset

import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.ibm.uclab.csrepl.client.CodestationClient
import com.ibm.uclab.csrepl.http.HttpClientWrapper
import org.apache.http.impl.client.DefaultHttpClient

import org.apache.log4j.BasicConfigurator
import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout

class Util {
    static configureLogging() {
        BasicConfigurator.resetConfiguration()
    
        def layout = new PatternLayout("%m%n")
        def appender = new ConsoleAppender(layout)
        Logger.getRootLogger().addAppender(appender)
        
        Logger.getRootLogger().setLevel(Level.WARN)
        Logger.getLogger("httpclient.wire.content").setLevel(Level.OFF)
        Logger.getLogger("com.ibm.uclab.csrepl.client.ops").setLevel(Level.INFO)
    }
    
    static getCodestationClient(mainServerUrl, forceUseMainServer, user, password) {
        def PROXY_HOST = System.env['PROXY_HOST']
        def PROXY_PORT = System.env['PROXY_PORT']
        if (PROXY_PORT != null) {
            PROXY_PORT = Integer.valueOf(PROXY_PORT)
        }
        def CODESTATION_URL = System.env['CODESTATION_URL']
        def CODESTATION_USE_PROXY = Boolean.valueOf(System.env['CODESTATION_USE_PROXY'])
    
        def useMainServer = forceUseMainServer || !CODESTATION_URL || CODESTATION_USE_PROXY

        def url = CODESTATION_URL
        if (useMainServer) {
            url = mainServerUrl
        }
        while (url.endsWith("/")) {
            url = url.substring(0, url.length - 1)
        }

        def builder = new HttpClientBuilder()
        if (PROXY_HOST && useMainServer) {
            builder.setProxyHost(PROXY_HOST)
            builder.setProxyPort(PROXY_PORT)
        }
        builder.setUsername(user)
        builder.setPassword(password)

        String verifyServerIdentityString = System.getenv().get("UC_TLS_VERIFY_CERTS");
        Boolean trustAllCerts = Boolean.valueOf(verifyServerIdentityString);
        builder.setTrustAllCerts(!trustAllCerts);

        builder.setPreemptiveAuthentication(true)

        def httpClient = builder.buildClient()
        def wrapper = new HttpClientWrapper(httpClient)
        wrapper.setTimeout(60 * 1000, 5 * 60 * 1000)
        def csc = new CodestationClient(url, wrapper)
        csc.start()
        return csc
    }
    
    static getCharset(pluginProps) {
        if (pluginProps['charset']) {
            return Charset.forName(pluginProps['charset'])
        }
        
        def AGENT_HOME = new File(System.env['AGENT_HOME'])
        def agentProps = new Properties()
        new File(AGENT_HOME, "conf/agent/installed.properties").withInputStream {
            agentProps.load(it)
        }
        if (agentProps['system.default.encoding']) {
            return Charset.forName(agentProps['system.default.encoding'])
        }

        return null
    }
    
    static parseUUID(id) {
        try {
            return UUID.fromString(id)
        }
        catch (IllegalArgumentException e) {
            return null
        }
    }

}