//
//  IChatUtils.m
//  MYUtilities
//
//  Created by Jens Alfke on 3/3/08.
//  Copyright 2008 Jens Alfke. All rights reserved.
//

#import "IChatUtils.h"
#import "iChatBridge.h"

@implementation IChatUtils


static iChatApplication *sIChatApp;

+ (void) initialize
{
    if( ! sIChatApp ) {
        sIChatApp = [SBApplication applicationWithBundleIdentifier: @"com.apple.iChat"];
        sIChatApp.timeout = 5*60; // in ticks
    }
}


+ (SBApplication*) app  {return sIChatApp;}
+ (BOOL) isRunning      {return sIChatApp.isRunning;}
+ (void) activate       {[sIChatApp activate];}


+ (iChatTextChat*) activeChat
{
    if( ! [sIChatApp isRunning] )
        return nil;
    SBElementArray *chats = sIChatApp.textChats;
    if( chats.count==0 )
        return nil;
    iChatTextChat *chat = [chats objectAtIndex: 0];
    if( ! chat.active )
        return nil;
    return chat;
}    

+ (NSString*) activeChatPartner
{
    iChatTextChat *chat = [self activeChat];
    if( ! chat )
        return nil;
    NSMutableArray *names = $marray();
    for( iChatBuddy *b in [chat participants] )
        [names addObject: (b.fullName ?: b.name)];
    return [names componentsJoinedByString: @", "];
}

+ (BOOL) sendMessage: (NSString*)msg
{
    iChatTextChat *chat = [self activeChat];
    if( ! chat )
        return NO;
    [sIChatApp send: msg to: chat];
    return YES;
}


@end
