#include "console_session.h"
#include <sys/un.h>
#include <stdlib.h>
#include "chat_window.h"
#include "util.h"


static void console_session_close(int * session)
{
	gdk_input_remove(*((int*)session));
	g_free(session);
}

void console_session_get_command(gpointer data, 
								gint source, 
								GdkInputCondition condition )
{
	char * contact_name;
	char * message;
	struct contact * remote_contact;
	short len;
	int pos = 0;
	int ret;

	if(read(source, &len, sizeof(short))<=0)
	{
		console_session_close((int*)data);
		return;
	}
	contact_name = alloca(len);
	if(read(source, contact_name, len)<=0)
	{
		console_session_close((int*)data);
		return;
	}
	if(read(source, &len, sizeof(short))<=0)
	{
		console_session_close((int*)data);
		return;
	}
	message = alloca(len);
	if(read(source, message, len)<=0)
	{
		console_session_close((int*)data);
		return;
	}

	remote_contact = find_contact_by_nick(contact_name);
	if(!remote_contact)
	{
		ret = -1;
		write(source, &ret, sizeof(int));
		return;
	}
	eb_chat_window_display_contact(remote_contact);
	remote_contact->chatwindow->perfered= 
			find_suitable_remote_account(remote_contact->chatwindow->perfered, 
										remote_contact->chatwindow->contact);
	if(!remote_contact->chatwindow->perfered)
	{
		ret = -2;
		write(source, &ret, sizeof(int));
		return;
	}

	gtk_editable_insert_text(GTK_EDITABLE(remote_contact->chatwindow->entry),
							 message, strlen(message), &pos);
	send_message(NULL, remote_contact->chatwindow);
	ret = 0;
	write(source, &ret, sizeof(int));

}

void console_session_init(gpointer data, gint source, GdkInputCondition condition )
{
	struct sockaddr_un remote;
	int len;
	int sock;
	int * listener = g_new0(int, 1);
	
	sock = accept(source, &remote, &len);
	*listener = gdk_input_add(sock, GDK_INPUT_READ,
								console_session_get_command, 
								(gpointer)listener);
}
