package com.flowdock.jenkins;

import com.flowdock.jenkins.exception.FlowdockException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.MalformedURLException;

public class FlowdockAPI {
    private String apiUrl;
    private String flowToken;

    public FlowdockAPI(String apiUrl, String flowToken) {
        this.apiUrl = apiUrl;
        this.flowToken = flowToken;
    }

    public void pushTeamInboxMessage(TeamInboxMessage msg) throws FlowdockException {
        try {
            doPost("/messages/team_inbox/", msg.asPostData());
        } catch(UnsupportedEncodingException ex) {
            throw new FlowdockException("Cannot encode request data: " + ex.getMessage());
        }
    }

    public void pushChatMessage(ChatMessage msg) throws FlowdockException {
        try {
            doPost("/messages/chat/", msg.asPostData());
        } catch(UnsupportedEncodingException ex) {
            throw new FlowdockException("Cannot encode request data: " + ex.getMessage());
        }
    }

    private void doPost(String path, String data) throws FlowdockException {
        URL url;
        HttpURLConnection connection = null;
        String flowdockUrl = apiUrl + path + flowToken;
        try {
            // create connection
            url = new URL(flowdockUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // send the request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(data);
            wr.flush();
            wr.close();

            if(connection.getResponseCode() != 200) {
                StringBuffer responseContent = new StringBuffer();
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                    String responseLine;
                    while ((responseLine = in.readLine()) != null) {
                        responseContent.append(responseLine);
                    }
                    in.close();
                } catch(Exception ex) {
                    // nothing we can do about this
                } finally {
                    throw new FlowdockException("Flowdock returned an error response with status " + connection.getResponseCode() + " " + connection.getResponseMessage() + ", " + responseContent.toString());
                }
            }
        } catch(MalformedURLException ex) {
            throw new FlowdockException("Flowdock API URL is invalid: " + flowdockUrl);
        } catch(ProtocolException ex) {
            throw new FlowdockException("ProtocolException in connecting to Flowdock: " + ex.getMessage());
        } catch(IOException ex) {
            throw new FlowdockException("IOException in connecting to Flowdock: " + ex.getMessage());
        }
    }
}

@@ -609,16 +609,32 @@
 Token = 
+parseFlowTokens(
 flowToke
@@ -630,24 +630,25 @@
 ns(flowToken
+)
 ;%0A    %7D%0A%0A   
@@ -2892,24 +2892,44 @@
 h status %22 +
+%0A                   
  connection.
@@ -2994,16 +2994,36 @@
 + %22, %22 +
+%0A                   
  respons
@@ -3041,16 +3041,44 @@
 String()
+ + %22%5Cn%5CnURL: %22 + flowdockUrl
 );%0A     
@@ -3512,32 +3512,32 @@
 .getMessage());%0A
-
         %7D%0A    %7D%0A
@@ -3535,11 +3535,507 @@
  %7D%0A    %7D
+%0A%0A    public static String parseFlowTokens(String flowTokens) %7B%0A        if(flowTokens == null)%0A            return %22%22;%0A        String%5B%5D tokens = flowTokens.split(%22,%22);%0A        String parsedTokens = %22%22;%0A        for(int i = 0; i %3C tokens.length; i++) %7B%0A            String token = tokens%5Bi%5D.trim();%0A            if(token.length() == 0) continue;%0A%0A            parsedTokens += token;%0A            if(i %3C tokens.length - 1)%0A                parsedTokens += %22,%22;%0A        %7D%0A        return parsedTokens;%0A    %7D
 %0A%7D%0A

Support posting to multiple flows: parsing token string