#import "AppDelegate.h"
#import "XMPPFramework.h"
#import "DDASLLogger.h"
#import "DDTTYLogger.h"
#import "DDLog.h"

static const int ddLogLevel = LOG_LEVEL_VERBOSE;

NSString * const XMPPAuthenticationMethodPlain = @"Plain";
NSString * const XMPPAuthenticationMethodDigestMD5 = @"Digest-MD5";

NSString * const OptionHostName = @"...";
NSUInteger const OptionPort = 5222;
BOOL const OptionOldSchoolSSL = NO;
NSString * const OptionJID = @"...@example.com";
NSString * const OptionAuthenticationMethod = @"Plain";
NSString * const OptionPassword = @"...";

@interface AppDelegate () <XMPPStreamDelegate>

@property (retain) XMPPStream *xmppStream;

@end

@implementation AppDelegate

- (void)_setUpLogging {
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
}

- (void)_setUpStream {
    self.xmppStream = [[XMPPStream alloc] init];
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    self.xmppStream.hostName = OptionHostName;
    self.xmppStream.hostPort = OptionPort;
    self.xmppStream.myJID = [XMPPJID jidWithString:OptionJID];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self _setUpLogging];
    [self _setUpStream];
        
    NSError *error = nil;
    if (OptionOldSchoolSSL)
        [self.xmppStream oldSchoolSecureConnect:&error];
    else
        [self.xmppStream connect:&error];
}

-(void)applicationWillTerminate:(NSNotification *)notification {
    [self.xmppStream removeDelegate:self];
    [self.xmppStream disconnect];
}

-(void)xmppStreamDidConnect:(XMPPStream *)sender {
    Class authClass = nil;
    if ([OptionAuthenticationMethod isEqual:XMPPAuthenticationMethodPlain])
        authClass = [XMPPPlainAuthentication class];
    else if ([OptionAuthenticationMethod isEqual:XMPPAuthenticationMethodDigestMD5])
        authClass = [XMPPDigestMD5Authentication class];
    else {
        DDLogWarn(@"Unrecognized auhthentication method '%@', falling back on Plain",
                  OptionAuthenticationMethod);
        authClass = [XMPPPlainAuthentication class];
    }
    id<XMPPSASLAuthentication> auth = [[authClass alloc] initWithStream:sender
                                                               password:OptionPassword];
    NSError *error = nil;
    if (![sender authenticate:auth error:&error])
        NSLog(@"Error authenticating: %@", error);
}

@end