package net.maxhorstmann.askthecrowds.services;

import java.io.UnsupportedEncodingException;

import net.maxhorstmann.askthecrowds.models.ApiResult;
import net.maxhorstmann.askthecrowds.models.Poll;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class BackendService {
	
	private final String baseUrl = "http://askthecrowds.cloudapp.net/api";

	public String createUser()	{
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost(baseUrl + "/users");
		HttpResponse response;
		
		try {
			response = httpclient.execute(post);
		    StatusLine statusLine = response.getStatusLine();
		    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
		    	return "created";
		    }
		} 
		catch (Exception ex)
		{
		}
		
		return "1234-5678-1234-5678";
		
	}
	
	public String postPoll(Poll poll) {
		
		Gson gson = new Gson();
		String json = gson.toJson(poll);
		
		HttpClient httpclient = new DefaultHttpClient();
		int timeout = 5;
		HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), timeout * 1000);
		HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout * 1000);
		
		HttpPost post = new HttpPost(baseUrl + "/polls");
		try {
			post.setEntity(new StringEntity(json));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		HttpResponse response;
		
		try {
			response = httpclient.execute(post);
		    StatusLine statusLine = response.getStatusLine();
		    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
				String jsonResult = EntityUtils.toString(response.getEntity());
				ApiResult result = gson.fromJson(jsonResult, ApiResult.class);
				return result.Payload;
				
		    }
		} 
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		return null;
		
		
	}
}

@@ -738,16 +738,66 @@
 t/api%22;%0D
+%0A%09private final int httpConnectionTimeout = 5000;%0D
 %0A%0D%0A%09publ
@@ -1495,38 +1495,45 @@
 etParams(), 
-timeout * 1000
+httpConnectionTimeout
 );%0D%0A%09%09HttpCo
@@ -1588,22 +1588,29 @@
 (), 
-timeout * 1000
+httpConnectionTimeout
 );%0D%0A

move to constant