package ncrashed.registration;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.omg.CORBA.portable.OutputStream;

import com.google.gson.Gson;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

import java.util.concurrent.Future;

@SideOnly(Side.SERVER)
public class AuthServer 
{
	public String serverUrl;
	public String serverMirrow;
	public static AuthServer instance;
	private AsyncHttpClient httpClient;
	
	public AuthServer(String serverUrl, String serverMirrow)
	{
		this.serverUrl = serverUrl;
		httpClient = new AsyncHttpClient();
		instance = this;
	}
	

	public <T extends Object, U extends Object> T 
		query(String queryUrl, String method, U obj, Class<T> objClass, boolean isMirrow)
	{
		Gson gson = new Gson();
		try
		{
			if(method.equals("GET"))
			{
				String params = "?";
				for (Field field : obj.getClass().getDeclaredFields()) 
				{
				    field.setAccessible(true);
				    Object value = field.get(obj); 
				    if (value != null) 
				    {
				    	params += field.getName() + "=" + value + "&";
				    }  
				}
				
				AsyncHttpClient.BoundRequestBuilder builder =
						httpClient.prepareGet((isMirrow ? serverMirrow : serverUrl) + queryUrl + params);
				
				
				Future<Response> f = builder.execute();
				Response resp = f.get();
				
				if(resp.getStatusCode() != 200)
				{
					// uncatchable?
					//throw new RestQueryException("Request error: " + Integer.toString(resp.getStatusCode()));
					System.out.println("Request error: " + Integer.toString(resp.getStatusCode()));
					return null;
				}
				
				httpClient.close();
				return gson.fromJson(resp.getResponseBody(), objClass);
			} else
			{
				AsyncHttpClient.BoundRequestBuilder builder =
						httpClient.preparePost((isMirrow ? serverMirrow : serverUrl) + queryUrl);
				
				builder.setBodyEncoding("utf-8");
				builder.setHeader("Content-Type", "application/json");
				builder.setHeader("Language", "en-US");
				builder.setBody(gson.toJson(obj));
				
				Future<Response> f = builder.execute();
				Response resp = f.get();
				
				if(resp.getStatusCode() != 200)
				{
					// uncatchable?
					//throw new RestQueryException("Request error: " + Integer.toString(resp.getStatusCode()));
					System.out.println("Request error: " + Integer.toString(resp.getStatusCode()));
					return null;
				}
				
				httpClient.close();
				return gson.fromJson(resp.getResponseBody(), objClass);			
			}
		} catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
