/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. 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.http

import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.FileEntity
import org.apache.http.impl.client.DefaultHttpClient

import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.IO

public class HttpHelper {

    static private DefaultHttpClient client
    
    static private DefaultHttpClient createHttpClient() {
        if (client == null) {
            HttpClientBuilder clientBuilder = new HttpClientBuilder();
            clientBuilder.setTrustAllCerts(true);
            client = clientBuilder.buildClient();
        }
        return client
    }
    
    static public void sendPostRequest(String url, File xmlFile) {
        def authToken = System.getenv("AUTH_TOKEN")
        
        println "Sending request to $url"

        DefaultHttpClient client = createHttpClient();
        
        HttpPost postMethod = new HttpPost(url);
        if (authToken) {
            postMethod.setHeader("Authorization-Token", authToken)
            postMethod.setHeader("Content-Type", "application/xml")
        }
        postMethod.setEntity(new FileEntity(xmlFile, "text/xml"));
    
        def httpResponse = client.execute(postMethod)
        def responseCode = httpResponse.getStatusLine().getStatusCode()
        if (isGoodResponseCode(responseCode)) {
            IO.copy(postMethod.getEntity().getContent(), System.out)
            println ""
        }
        else {
            IO.copy(postMethod.getEntity().getContent(), System.err)
            throw new RuntimeException("Upload to server failed. StatusCode: ${responseCode}")
        }
    }
    
    static private boolean isGoodResponseCode(int responseCode) {
        return responseCode >= 200 && responseCode < 300;
    }
    
    static public def getChangeSets() {
        def authToken = System.getenv("AUTH_TOKEN")
        int buildLifeId = Integer.parseInt(System.getenv("BUILD_LIFE_ID"))
        String webUrl = System.getenv("WEB_URL")
        webUrl += webUrl.endsWith("/") ? "" : "/"
        
        String changesRequestUrl = webUrl + "rest/buildlife/${buildLifeId}/sourcechanges"
        
        println "Getting source changes from server"
        
        DefaultHttpClient client = createHttpClient();
        HttpGet getMethod = new HttpGet(changesRequestUrl);
        if (authToken) {
            getMethod.setHeader("Authorization-Token", authToken)
            getMethod.setHeader("Content-Type", "application/xml")
        }
    
        def httpResponse = client.execute(getMethod)
        def responseCode = httpResponse.getStatusLine().getStatusCode()
        InputStream responseStream = httpResponse.entity.content
        String changesXml = IO.readText(responseStream)
        if (!isGoodResponseCode(responseCode)) {
            throw new Exception("Failed to get build life source changes from the server: $changesXml")
        }
        return changesXml
    }
    
    static public def getIssuesXml() {
        def authToken = System.getenv("AUTH_TOKEN")
        int buildLifeId = Integer.parseInt(System.getenv("BUILD_LIFE_ID"))
        String webUrl = System.getenv("WEB_URL")
        webUrl += webUrl.endsWith("/") ? "" : "/"
        
        String issuesRequestUrl = webUrl + "rest/buildlife/${buildLifeId}/issues"
        
        println "Getting issues from server"
        
        DefaultHttpClient client = createHttpClient();
        HttpGet getMethod = new HttpGet(issuesRequestUrl);
        if (authToken) {
            getMethod.setHeader("Authorization-Token", authToken)
            getMethod.setHeader("Content-Type", "application/xml")
        }
        
        def httpResponse = client.execute(getMethod)
        def responseCode = httpResponse.getStatusLine().getStatusCode()
        InputStream responseStream = httpResponse.entity.content
        String issuesXml = IO.readText(responseStream)
        if (!isGoodResponseCode(responseCode)) {
            throw new Exception("Failed to get build life issues from the server: $issuesXml")
        }
        return issuesXml
    }
}