/*
* Li/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2011, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
/* This is an example step groovy to show the proper use of APTool
 * In order to use import these utilities, you have to use the "pluginutilscripts" jar
 * that comes bundled with this plugin example.
 */
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper

import com.urbancode.air.*
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder;

import com.urbancode.air.XTrustProvider;
import java.net.URI;
import java.nio.charset.Charset;

import com.urbancode.release.rest.framework.Clients;
import com.urbancode.release.rest.models.internal.PluginIntegrationProvider;
import com.urbancode.release.rest.models.AuthenticationRealm;
import com.urbancode.release.rest.models.LdapAuthenticationRealm;
import com.urbancode.release.rest.models.internal.ScheduledDeployment;
import com.urbancode.release.rest.models.internal.TaskExecution;

import com.urbancode.air.*
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.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import com.urbancode.air.PropsParser;
import com.urbancode.air.UCRPropsUtil;

import java.net.URI;

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

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

//Required to access Release endpoints
def releaseToken = props['releaseToken'];
def extraProperties = props['extraProperties'];
//Useful for some operations
//it gets the ID of the integration provider running that step
def integrationProviderId = props['releaseIntegrationProvider'];

//All fields saved from the UI
//to be added automatically by the server
def serverUrl = props['releaseServerUrl'];

// Establish the client connection
Clients.loginWithToken(serverUrl, releaseToken);

def ucrPropsUtil = new UCRPropsUtil();
def propsParser = new PropsParser();
def slackMessage = props['message'];
def slackChannel = props['hookUrl'];
def proxyHost = props['proxyHost'];
def proxyPort = props['proxyPort'];
def proxyUser = props['proxyUser'];
def proxyPass = props['proxyPass'];
def task;
def sdId = null;
if (extraProperties != null) {
    def slurper = new groovy.json.JsonSlurper()
    def currentTaskExtra = slurper.parseText(extraProperties)

    if (currentTaskExtra != null) {
        //We need the ucr task if so we can handle that UCR object later
        def urcTaskId = currentTaskExtra.task.id

        task = new TaskExecution()
        task.id(urcTaskId)
        task = task.get()
        //We will need the user to create comments
        def userId = currentTaskExtra.userId

        slackMessage = task.getProperty("message")
        sdId = currentTaskExtra.task.scheduledDeploymentId
        ScheduledDeployment sdDetail = new ScheduledDeployment();
        sdDetail = sdDetail.id(sdId)
        sdDetail.format("detail")
        sdDetail = sdDetail.get()

        def extraData = ucrPropsUtil.getExtraProperties(props, sdDetail, task)

        slackMessage = propsParser.parseSingleValue(slackMessage, extraData, sdDetail, task)

        println "Task Message = "+slackMessage
        if (currentTaskExtra.task.pluginProperties.slackMessage != null) {
            slackMessage = currentTaskExtra.task.pluginProperties.slackMessage;
        }

        if (currentTaskExtra.task.pluginProperties.hookUrl != null) {
            slackChannel = currentTaskExtra.task.pluginProperties.hookUrl;
        }
    }
}

Clients.loginWithToken(serverUrl, releaseToken);

HttpClientBuilder builder = new HttpClientBuilder();
builder.setTrustAllCerts(true);

if (proxyHost) {
    builder.setProxyHost(proxyHost)
    builder.setProxyPort(Integer.valueOf(proxyPort))

    if (proxyUser) {
        builder.setProxyUsername(proxyUser)
        builder.setProxyPassword(proxyPass)
    }
}

def client = builder.buildClient();

HttpPost methodPost = new HttpPost(slackChannel);
String message = "{'text':'"+slackMessage+"'}"
methodPost.addHeader("Accept", "application/json")
methodPost.addHeader("Content-Type", "application/json")
StringEntity postEntity = new StringEntity(message)
methodPost.setEntity(postEntity)

HttpResponse responsePost = client.execute(methodPost);

int status = responsePost.getStatusLine().getStatusCode();

println("RESPONSE CODE=>"+responsePost.getStatusLine().getStatusCode())
if (responsePost.getStatusLine().getStatusCode() == 200) {

    String resultBody = EntityUtils.toString(responsePost.getEntity());
    EntityUtils.consume(responsePost.getEntity());

    if (resultBody != null) {
        println("RESPONSE BODY=>"+resultBody)
    }

    if (task != null) {
        task.complete()
    }
}
else {
    if (task != null) {
        task.fail()
    }
}
