package com.sendsms.Parsing;

import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.util.List;

public class ServerCommunication {

	public static JSONObject callJson(String url, JSONObject parameters) throws Exception
	{
		Log.d("url",url);


		HttpClient client = new DefaultHttpClient();
		InputStream in = null;
		
		HttpPost post = new HttpPost(url);
		StringEntity se = null;
		HttpResponse response = null;
		JSONObject json = null;
		
		
		try {
			
			se = new StringEntity(parameters.toString());
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
			post.setEntity(se);
			response = client.execute(post);
			
			if (response != null) 
			{
				in = response.getEntity().getContent();
			}
			String data = Validations.inputSteamToString(in);
			
			Log.d("Response String", data);
			
			json = new JSONObject(data);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return json;

	}

	public static String post(String url, List<NameValuePair> nameValuePairs) throws Exception
	{
	    HttpClient httpClient = new DefaultHttpClient();
	    InputStream in = null;
	    HttpContext localContext = new BasicHttpContext();
	    HttpPost httpPost = new HttpPost(url);

	    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);


	    for(int index=0; index < nameValuePairs.size(); index++) 
	    {
	    	if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) 
	    	{
	    		entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue())));
	    	}
	    	else 
	    	{
	    		entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
	    	}
	    }

	    httpPost.setEntity(entity);

	    HttpResponse response = httpClient.execute(httpPost, localContext);
	    if (response != null) 
	    {
	    	in = response.getEntity().getContent();
	    }

	    String data = Validations.inputSteamToString(in);
				
	    Log.d("Response String",data);
						
	    return data;	 	   
	}
}
