import java.io.IOException;
import java.io.StringReader;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

/*
 * This sample demonstrates how to trigger a build.
 * 
 * IMPORTANT: Make sure to check QuickBuild server log if you get exceptions reporting 
 * a 500 response status.
 */
public class TriggerBuild {
    public static void main(String[] args) throws IOException, DocumentException {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));
        String configurationId = client.resource("http://localhost:8810/rest/ids")
        		.queryParam("configuration_path", "root/test").get(String.class);

        String buildRequest =
                "<com.pmease.quickbuild.BuildRequest>" +
                "  <configurationId>" + configurationId + "</configurationId>" +
                "  <respectBuildCondition>false</respectBuildCondition>" +
                "  <variables>" +
                "    <entry>" +
                "      <string>version</string>" +
                "      <string>2.0.0</string>" +
                "    </entry>" +
                "  </variables>" +
                "</com.pmease.quickbuild.BuildRequest>";

        ClientResponse response = client.resource("http://localhost:8810/rest/build_requests")
				.post(ClientResponse.class, buildRequest);

        if (response.getStatus() == 204) {
        	System.out.println("Requested build is aggregated.");
        	return;
        } else if (response.getStatus() != 200) { 
    		throw new RuntimeException("Error requesting build: " + response.getEntity(String.class));
        }

        Document dom = new SAXReader().read(new StringReader(response.getEntity(String.class)));
        String requestId = dom.getRootElement().elementText("requestId");
        
        // Optionally waiting for build id to be generated
        WebResource resource = client.resource("http://localhost:8810/rest/ids")
        		.queryParam("request_id", requestId);
        response = resource.get(ClientResponse.class);
        while (response.getStatus() == 204) { // no content means build id is not generated yet
        	try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
			}
			response = resource.get(ClientResponse.class);
        }
    	if (response.getStatus() != 200) 
    		throw new RuntimeException("ERROR: " + response.getEntity(String.class));

    	String buildId = response.getEntity(String.class);
    	
        // Optionally waiting for build to be finished
        resource = client.resource("http://localhost:8810/rest/builds/" + buildId + "/status");
        String buildStatus = resource.get(String.class);
        while (buildStatus.equals("RUNNING")) {
        	try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
			}
			buildStatus = resource.get(String.class);
        }

        String buildVersion = client.resource("http://localhost:8810/rest/builds/" + buildId + "/version")
        		.get(String.class);

        System.out.println("Build done (build: " + buildVersion + ", status: " + buildStatus + ")");
    }
}
