package com.playlist;

import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL.
 */
public class SlackClient {

    private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL");

    public void postMessageToSlack(String message) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost httpPost = new HttpPost(slackWebHookUrl);

            JSONObject json = new JSONObject();
            json.put("text", message);
            json.put("channel", "#test-integrations");//TODO: remove channel override

            StringEntity entity = new StringEntity(json.toString());

            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                if(response.getStatusLine().getStatusCode() != 200) {
                    throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity()));
                }
            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }
    }
}

@@ -47,16 +47,60 @@
 Object;%0A
+import org.apache.commons.lang.StringUtils;%0A
 import o
@@ -152,16 +152,16 @@
 sponse;%0A
-
 import o
@@ -588,16 +588,99 @@
 K_URL%22);
+%0A    private String slackChannelOverride = System.getenv(%22SLACK_CHANNEL_OVERRIDE%22);
 %0A%0A    pu
@@ -979,16 +979,17 @@
 ssage);%0A
+%0A
         
@@ -996,81 +996,195 @@
     
-json.put(%22channel%22, %22#test-integrations%22);//TODO: remove c
+//Include a channel override if one has been provided%0A            if(!StringUtils.isEmpty(slackChannelOverride)) %7B%0A                json.put(%22channel%22, slackC
 hannel
- o
+O
 verride
+);%0A            %7D
 %0A%0A  

Refactor channel override to environment variable.