#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (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 com.urbancode.air.*

import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;

import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder;

import com.urbancode.air.XTrustProvider;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient
import org.apache.http.client.*
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

final def workDir = new File('.').canonicalFile

def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();

def oslcUrl = props['oslcUrl']
def oslcKey = props['oslcKey']
def oslcSecret = props['oslcSecret']
def projectArea = props['projectArea']

def jsonArray = null;

try {
    println "URL:"+oslcUrl
	println "Project Area:"+projectArea
    
    if (projectArea != null) {
        projectArea = projectArea.replace(" ", "%20");
    }
	 
    HttpClientBuilder builder = new HttpClientBuilder();
    builder.setTrustAllCerts(true);

    def client = builder.buildClient();
    
    HttpGet methodGet = new HttpGet(oslcUrl);
    HttpResponse responseGet = client.execute(methodGet);
    
    int status = responseGet.getStatusLine().getStatusCode();
    
    if (status == HttpStatus.SC_OK) {
        println "The connection was successful";
    }
    else {
        //We throw an error if we can not connect to that URL it will be displayed in red on the integration provider page
        throw new Exception(String.format("%d", status));
    }
    
    println "-------------------------------------------------------------------------------"
    println "Connection Successful"
    println "-------------------------------------------------------------------------------"
}
catch (e) {
    def analysedOutput = generateHelpMessageFromError (e.getMessage());
	println "-------------------------------------------------------------------------------"
	println "Connection Failed"+analysedOutput
    println analysedOutput
	println "-------------------------------------------------------------------------------"
    throw new Exception("Error connecting to the RTC Server <br/>"+e.getMessage());
}

def generateHelpMessageFromError (msg) {
    def helpMessage = "";
    if (msg.contains("Can not create the OAuth Client")) {
        helpMessage+="The RTC instance seems to be not accessible from " +
                        "the IBM UrbanCode Release server <br />";
        helpMessage+="The URL might not be following the pattern: http://host:port/ccm/<br />";
    }

    if (msg.contains("invalid_consumer_key")) {
        helpMessage+="The Consumer Key and Secret may have been created in the jts/admin instead of ccm/admin<br />";
        helpMessage+="The User used to create the Consumer might not be the Admin user<br />";
        helpMessage+="The Consumer Key is incorrect<br />";
    }

    if (msg.contains("invalid_expired_token")) {
        helpMessage+="The User used to create the Consumer might not be the Admin user<br />";
        helpMessage+="The Trusted option might not have been checked for that Consumer<br />";
    }

    if (msg.contains("signature_invalid")) {
        helpMessage+="The Consumer Secret is incorrect<br />";;
    }

    if (msg.contains("timestamp_refused")) {
        helpMessage+="The Servers hosting IBM UrbanCode Release and RTC have a time difference longer than supported<br />";
    }
    return helpMessage;
}