#import "JubGtkRosterUI.h"
#import "JubGObjectMap.h"
#import "JubGtkChatUI.h"
#import "JubGtkHelper.h"

static gboolean roster_row_activated(GtkTreeView *tree_view, GtkTreePath *path,
    GtkTreeViewColumn *column, gpointer data)
{
	JubGtkRosterUI *roster = data;
	GtkTreeIter row_iter;
	GtkTreeModel *tree_model;
	gchar *jid_s;
	XMPPJID *jid;
	OFAutoreleasePool *pool;

	tree_model = gtk_tree_view_get_model(tree_view);
	gtk_tree_model_get_iter(tree_model, &row_iter, path);
	gtk_tree_model_get(tree_model, &row_iter, 1, &jid_s, -1);

	// This was a group row
	if (!jid_s) return TRUE;

	pool = [OFAutoreleasePool new];
	jid = [XMPPJID JIDWithString: [OFString stringWithUTF8String: jid_s]];

	[roster performSelectorOnMainThread: @selector(chatForJID:)
				 withObject: jid
			      waitUntilDone: NO];
	[pool release];

	return TRUE;
}

static gboolean filter_roster_by_presence(GtkTreeModel *model,
    GtkTreeIter *iter, gpointer data)
{
	char *jid_s;
	OFString *jid;
	OFCountedSet *presences = data;

	gtk_tree_model_get(model, iter, 1, &jid_s, -1);

	// Groups have no JID
	if (!jid_s)
		return TRUE;

	jid = [[OFString alloc] initWithUTF8String: jid_s];

	g_free(jid_s);

	int num = [presences countForObject: jid];
	if (num) {
		[jid release];
		return TRUE;
	} else {
		[jid release];
		return FALSE;
	}
}

@implementation JubGtkRosterUI
- initWithBuilder: (GtkBuilder*)builder_
       connection: (XMPPConnection*)connection_
{
	self = [super init];

	@try {
		GtkTreeView *roster_view;

		groupMap = [[OFMapTable alloc]
		    initWithKeyFunctions: keyFunctions
			  valueFunctions: rowRefFunctions];
		contactMap = [[OFMutableDictionary alloc] init];
		chatMap = [[OFMutableDictionary alloc] init];
		presences = [[OFCountedSet alloc] init];
		connection = [connection_ retain];

		builder = g_object_ref(builder_);

		roster_model = GTK_TREE_STORE(gtk_builder_get_object(builder,
		    "RosterTreeStore"));

		roster_filter = GTK_TREE_MODEL_FILTER(
		    gtk_builder_get_object(builder, "RosterTreeModelFilter"));

		gtk_tree_model_filter_set_visible_func(roster_filter,
		    filter_roster_by_presence, presences, NULL);

		roster_view = GTK_TREE_VIEW(gtk_builder_get_object(builder,
			"RosterTreeView"));

		g_signal_connect(roster_view, "row_activated",
		    G_CALLBACK(roster_row_activated), self);
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[groupMap release];
	[contactMap release];
	[presences release];
	[connection release];

	if (roster_model)
		g_object_unref(roster_model);

	if (roster_filter)
		g_object_unref(roster_filter);

	g_object_unref(builder);

	[super dealloc];
}

/* Presence handling */
-   (void)connection: (XMPPConnection*)connection
  didReceivePresence: (XMPPPresence*)presence
{
	if ([presence.type isEqual: @"available"])
		[presences addObject: [presence.from bareJID]];
	else if ([presence.type isEqual: @"unavailable"])
		[presences removeObject: [presence.from bareJID]];

	g_idle_add_block(^{
		gtk_tree_model_filter_refilter(roster_filter);
	});
}

// FIXME: This needs to move somewhere else
- (JubGtkChatUI*)chatForJID: (XMPPJID*)jid
{
	OFAutoreleasePool *pool = [OFAutoreleasePool new];
	JubGtkChatUI *chat =
	    [chatMap objectForKey: [jid bareJID]];
	if (chat == nil) {
		OFString * title = [@"Chat with " stringByAppendingString:
		    [jid bareJID]];

		chat = [[[JubGtkChatUI alloc]
		    initWithTitle: title
		       closeBlock: ^{
				[chatMap removeObjectForKey: [jid bareJID]];
			}
			sendBlock: ^(OFString *text) {
				XMPPMessage *msg =
				    [XMPPMessage messageWithType: @"chat"];
				msg.to = jid;
				msg.body = text;
				[connection sendStanza: msg];
			}
		] autorelease];

		[chatMap setObject: chat
			    forKey: [jid bareJID]];
	}

	[pool release];

	return chat;
}

-  (void)connection: (XMPPConnection*)connection
  didReceiveMessage: (XMPPMessage*)message
{
	JubGtkChatUI *chat = [self chatForJID: message.from];
	[chat addMessage: message.body
		  sender: [message.from bareJID]];
}

/* Roster Delegate methods */
- (void)Jub_addRosterItem: (XMPPRosterItem*)item
		    group: (OFString*)group
{
	g_idle_add_block(^{
		GtkTreeIter group_iter, contact_iter;
		GtkTreeRowReference *group_ref, *contact_ref;
		GtkTreePath *group_path, *contact_path;
		OFMapTable *contactRows =
		    [contactMap objectForKey: [item.JID bareJID]];

		group_ref = [groupMap valueForKey: group];

		if (!group_ref) {
			// Create new group row
			gtk_tree_store_append(roster_model, &group_iter, NULL);
			gtk_tree_store_set(roster_model, &group_iter,
			    0, [group UTF8String], -1);

			group_path = gtk_tree_model_get_path(GTK_TREE_MODEL(
				roster_model), &group_iter);

			group_ref = gtk_tree_row_reference_new(GTK_TREE_MODEL(
				roster_model), group_path);

			[groupMap setValue: group_ref
				    forKey: group];
		} else {
			// Get iter for existing group row
			group_path = gtk_tree_row_reference_get_path(group_ref);

			gtk_tree_model_get_iter(GTK_TREE_MODEL(roster_model),
			    &group_iter, group_path);
		}
		gtk_tree_path_free(group_path);

		// Create new contact row
		gtk_tree_store_append(roster_model, &contact_iter, &group_iter);
		if (item.name)
			gtk_tree_store_set(roster_model, &contact_iter,
			    0, [item.name UTF8String],
			    1, [[item.JID bareJID] UTF8String], -1);
		else
			gtk_tree_store_set(roster_model, &contact_iter,
			    0, [item.JID.node UTF8String],
			    1, [[item.JID bareJID] UTF8String], -1);

		contact_path = gtk_tree_model_get_path(GTK_TREE_MODEL(
			roster_model), &contact_iter);

		contact_ref = gtk_tree_row_reference_new(GTK_TREE_MODEL(
			roster_model), contact_path);

		gtk_tree_path_free(contact_path);

		[contactRows setValue: contact_ref
			       forKey: group];
	});
}

- (void)Jub_removeRosterItem: (XMPPRosterItem*)item
		       group: (OFString*)group
{
	g_idle_add_block(^{
		GtkTreeIter contact_iter, group_iter;
		GtkTreePath *contact_path, *group_path;
		GtkTreeRowReference *contact_ref, *group_ref;
		OFMapTable *contactRows =
		    [contactMap objectForKey: [item.JID bareJID]];

		contact_ref = [contactRows valueForKey: group];
		contact_path = gtk_tree_row_reference_get_path(contact_ref);
		gtk_tree_model_get_iter(GTK_TREE_MODEL(roster_model),
		    &contact_iter, contact_path);

		gtk_tree_store_remove(roster_model, &contact_iter);

		group_ref = [groupMap valueForKey: group];
		group_path = gtk_tree_row_reference_get_path(group_ref);
		gtk_tree_model_get_iter(GTK_TREE_MODEL(roster_model),
		    &group_iter, group_path);

		if (!gtk_tree_model_iter_has_child(GTK_TREE_MODEL(roster_model),
		    &group_iter)) {
			gtk_tree_store_remove(roster_model, &group_iter);
			[groupMap removeValueForKey: group];
		}

		gtk_tree_path_free(group_path);
	});
}

- (void)rosterWasReceived: (XMPPRoster*)roster_
{
	of_log(@"Handling roster");
	[[roster_ rosterItems] enumerateKeysAndObjectsUsingBlock:
	    ^(OFString *bareJID, XMPPRosterItem *item, BOOL *stop) {
		OFArray *groups;
		OFMapTable *contactRows = [OFMapTable
		    mapTableWithKeyFunctions: keyFunctions
			      valueFunctions: rowRefFunctions];

		[contactMap setObject: contactRows
			       forKey: bareJID];

		if (item.groups != nil)
			groups = item.groups;
		else
			groups = @[@"General"];

		for (OFString *group in groups)
			[self Jub_addRosterItem: item
					  group: group];
	}];
}

-         (void)roster: (XMPPRoster*)roster_
  didReceiveRosterItem: (XMPPRosterItem*)item
{
	OFArray *groups;
	XMPPRosterItem *oldItem =
	    [roster_.rosterItems objectForKey: [item.JID bareJID]];

	if (oldItem) {
		if (oldItem.groups != nil)
			groups = oldItem.groups;
		else
			groups = @[@"General"];

		for (OFString *group in groups)
			[self Jub_removeRosterItem: oldItem
					     group: group];

		[contactMap removeObjectForKey: [item.JID bareJID]];
	}

	if (![item.subscription isEqual: @"remove"]) {
		OFMapTable *contactRows = [OFMapTable
		    mapTableWithKeyFunctions: keyFunctions
			      valueFunctions: rowRefFunctions];

		[contactMap setObject: contactRows
			       forKey: [item.JID bareJID]];

		if (item.groups != nil)
			groups = item.groups;
		else
			groups = @[@"General"];

		for (OFString *group in groups)
			[self Jub_addRosterItem: item
					  group: group];
	}
}

@end
