#import <ObjFW/ObjFW.h>
#import <ObjXMPP/ObjXMPP.h>

#import "JubGtkUI.h"
#import "JubCLIUI.h"
#import "JubConfig.h"
#import "JubChatClient.h"

@interface AppDelegate: OFObject <OFApplicationDelegate, XMPPConnectionDelegate>
{
	JubChatClient *_client;
	id<JubUI> _ui;
}
@end

OF_APPLICATION_DELEGATE(AppDelegate)

@implementation AppDelegate
- (void)applicationDidFinishLaunching
{
	JubConfig *config = [[[JubConfig alloc] initWithFile: @"config.xml"]
	    autorelease];

	_client = [[JubChatClient alloc] initWithConfig: config];

	if ([config.frontend isEqual: @"gtk"])
		_ui = [[JubGtkUI alloc] initWithClient: _client];
	else if ([config.frontend isEqual: @"cli"])
		_ui = [[JubCLIUI alloc] initWithClient: _client];
	else {
		[of_stderr writeFormat: @"Unknown frontend '%@', known "
		    @"frontends are 'gtk' and 'cli'\n", config.frontend];
		[OFApplication terminate];
	}

	_client.ui = _ui;
	[_client.connection addDelegate: self];

	[_ui startUIThread];
	[_client.connection asyncConnectAndHandle];
}

-  (void)connection: (XMPPConnection*)connection
  didReceiveElement: (OFXMLElement*)element
{
	of_log(@"In:  %@", element);
}

- (void)connection: (XMPPConnection*)connection
    didSendElement: (OFXMLElement*)element
{
	of_log(@"Out: %@", element);
}

-  (void)connection: (XMPPConnection*)connection
  didThrowException: (id)e
{
	@throw e;
}
@end
