package GetAction;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;

import System.Sys;
import basicClass.Event;
import basicClass.Message;

public class GetMessage {
	HttpParams params;
	BasicHttpProcessor httpproc;
	HttpRequestExecutor httpexecutor;
	HttpContext context;
	HttpHost host;
	DefaultHttpClientConnection conn;
	ConnectionReuseStrategy connStrategy;
	
	public GetMessage() {
		params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);
        
        httpproc = new BasicHttpProcessor();
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());
        
        httpexecutor = new HttpRequestExecutor();
        context = new BasicHttpContext(null);
        host = new HttpHost("localhost", 8080);
        conn = new DefaultHttpClientConnection();
        connStrategy = new DefaultConnectionReuseStrategy();
        
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
	}
	
	public List<Message> getMessageByEid(int eid) throws Exception{
		List<Message> messages = null;
		try {
			HashMap<String,Object> param_entity = new HashMap<String, Object>();
			param_entity.put(Sys.GET_METHOD, Sys.GET_METHOD_EID);
			param_entity.put(Sys.PARAM_NAME_EID, eid);
			
			ByteArrayOutputStream baos_post = new ByteArrayOutputStream();
			ObjectOutputStream oos_post = new ObjectOutputStream(baos_post);
			oos_post.writeObject(param_entity);
			oos_post.flush();
			byte[] buffer_post = baos_post.toByteArray();
			oos_post.close();
			
			HttpEntity requestBody = new ByteArrayEntity(buffer_post);
			
			if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", 
                    "/eventbook/doServlet/GetMessage");
                request.setEntity(requestBody);
                
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());

                request.setParams(params);
                //context.setAttribute("type", type);
                httpexecutor.preProcess(request, httpproc, context);
                HttpResponse response = httpexecutor.execute(request, conn, context);
                response.setParams(params);
                //response.addHeader("Content-Length", buffer.length + "");
                response.setHeader("Content-type", "application/octec-stream");
                httpexecutor.postProcess(response, httpproc, context);
        
                System.out.println("<< Response: " + response.getStatusLine());
                //System.out.println(EntityUtils.toString(response.getEntity()));
                System.out.println("==============");
                
                byte[] buffer = new byte[(int)response.getEntity().getContentLength()];
                response.getEntity().getContent().read(buffer);
                ByteArrayInputStream baos = new ByteArrayInputStream(buffer);
                ObjectInputStream oos = new ObjectInputStream(baos);
                try {
                	messages = (List<Message>)oos.readObject();
                }catch(ClassNotFoundException e) {
                	e.toString();
                	e.printStackTrace();
                }
                
                
                if (!connStrategy.keepAlive(response, context)) {
                    conn.close();
                } else {
                    System.out.println("Connection kept alive...");
                }
			}
            } finally {
                conn.close();
            }       
		return messages;
	}
	
	public List<Message> getMessageByUid(int uid) throws Exception{
		List<Message> messages = null;
		try {
			HashMap<String,Object> param_entity = new HashMap<String, Object>();
			param_entity.put(Sys.GET_METHOD, Sys.GET_METHOD_UID);
			param_entity.put(Sys.PARAM_NAME_UID, uid);
			
			ByteArrayOutputStream baos_post = new ByteArrayOutputStream();
			ObjectOutputStream oos_post = new ObjectOutputStream(baos_post);
			oos_post.writeObject(param_entity);
			oos_post.flush();
			byte[] buffer_post = baos_post.toByteArray();
			oos_post.close();
			
			HttpEntity requestBody = new ByteArrayEntity(buffer_post);
			
			if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", 
                    "/eventbook/doServlet/GetMessage");
                request.setEntity(requestBody);
                
                System.out.println(">> Request URI: " + request.getRequestLine().getUri());

                request.setParams(params);
                //context.setAttribute("type", type);
                httpexecutor.preProcess(request, httpproc, context);
                HttpResponse response = httpexecutor.execute(request, conn, context);
                response.setParams(params);
                //response.addHeader("Content-Length", buffer.length + "");
                response.setHeader("Content-type", "application/octec-stream");
                httpexecutor.postProcess(response, httpproc, context);
        
                System.out.println("<< Response: " + response.getStatusLine());
                //System.out.println(EntityUtils.toString(response.getEntity()));
                System.out.println("==============");
                
                byte[] buffer = new byte[(int)response.getEntity().getContentLength()];
                response.getEntity().getContent().read(buffer);
                ByteArrayInputStream baos = new ByteArrayInputStream(buffer);
                ObjectInputStream oos = new ObjectInputStream(baos);
                try {
                	messages = (List<Message>)oos.readObject();
                }catch(ClassNotFoundException e) {
                	e.toString();
                	e.printStackTrace();
                }
                
                
                if (!connStrategy.keepAlive(response, context)) {
                    conn.close();
                } else {
                    System.out.println("Connection kept alive...");
                }
			}
            } finally {
                conn.close();
            }       
		return messages;
	}
	
	
	
	
}
