//
//  FrictionlessKeyChainBridge.m
//  RubyFrictionless
//
//  Created by Pierce T. Wetter III on 2/26/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "FrictionlessKeyChainBridge.h"
#import <Security/Security.h>
#include <execinfo.h>

@implementation FrictionlessKeyChainBridge

+ (void) addServerName: (NSString *) serverName account: (NSString *) account password:(NSString *) password
{
	const char *serviceCSTR=[serverName UTF8String];
	const char *accountCSTR=[account UTF8String];
	const char *passwordCSTR=[password UTF8String];
	NSLog(@"adding password");
	OSStatus result=SecKeychainAddGenericPassword (
											nil,
											strlen(serviceCSTR),
											serviceCSTR,
											strlen(accountCSTR),
											accountCSTR,
											strlen(passwordCSTR),
											passwordCSTR,
											nil);
}
+ (NSString *) findPasswordForServer: (NSString *) serverName account: (NSString *) account
{
	if (!account) return @"";
	if (!serverName) return @"";
	const char *serviceCSTR=[serverName UTF8String];
	const char *accountCSTR=[account UTF8String];
	char *password;
	UInt32 length=0;
	NSLog(@"fetching password %@ %@",serverName,account);
	OSStatus result=SecKeychainFindGenericPassword (
											 nil,
											 strlen(serviceCSTR),
											 serviceCSTR,
											 strlen(accountCSTR),
											 accountCSTR,
											 &length,
											 (void **) &password,
											 nil);
	
	NSLog(@"fetchedpassword");
	if (length > 0)
	{
		NSString *passwordNS;
		passwordNS=[[NSString alloc] initWithBytes:password length:length encoding: NSUTF8StringEncoding];
		[passwordNS autorelease];
		return passwordNS;
	}
	return nil;
}


@end


#import "Mail.h"
@interface SBSendEmail : NSObject 
{}
@end
@implementation SBSendEmail

+ getMessageIdFrom: (id) message
{
	return [message messageId]; 
}

+ (id) sendEmailMessageFrom: (NSString *) from to: (NSString *) toAddress subject:(NSString *) subject content:(NSString *) content send: (bool) doSend
{	
	/* create a Scripting Bridge object for talking to the Mail application
	 */
    MailApplication *mail = [SBApplication
							 applicationWithBundleIdentifier:@"com.apple.Mail"];
    
	/* create a new outgoing message object */
    MailOutgoingMessage *emailMessage =
	[[[mail classForScriptingClass:@"outgoing message"] alloc]
	 initWithProperties:
	 [NSDictionary dictionaryWithObjectsAndKeys:
	  subject, @"subject",
	  content, @"content",
	  nil]];
	
	/* add the object to the mail app  */
    [[mail outgoingMessages] addObject: emailMessage];
    
	/* set the sender, show the message */
    emailMessage.sender = from;
    if (!doSend) emailMessage.visible = YES;
	
	/* create a new recipient and add it to the recipients list */
    MailToRecipient *theRecipient =
	[[[mail classForScriptingClass:@"to recipient"] alloc]
	 initWithProperties:
	 [NSDictionary dictionaryWithObjectsAndKeys:
	  toAddress, @"address",
	  nil]];
    [emailMessage.toRecipients addObject: theRecipient];
    
	if (doSend)
	{
		if ([emailMessage send])
		{
			
			NSPredicate *findBySubject=[NSPredicate predicateWithFormat:@"subject == %@", subject];
#define ATTEMPTS 5      // try 5 times to get a match against the sent mail box, so we can get a message ID back.
			for (int i=0;i< ATTEMPTS;i++)
			{
				NSArray *result = [[[mail sentMailbox] messages] filteredArrayUsingPredicate: findBySubject];
				if ([result count])
					return [result lastObject];
				else
					sleep(5); // sleep 5 seconds in hopes of getting a message ID Back
			}
		}
	}
	else
		[mail activate];
	return nil;
}

@end

@interface StackDumper : NSObject
{}
+ (void) dumpStack;
@end
@implementation StackDumper
+ (void) dumpStack
{
	void *backtraceFrames[128];
	int frameCount = backtrace(&backtraceFrames[0], 128);
	char **frameStrings = backtrace_symbols(&backtraceFrames[0], frameCount);
	
	if(frameStrings != NULL) {
		int x = 0;
		for(x = 0; x < frameCount; x++) {
			if(frameStrings[x] == NULL) { break; }
			printf("%s\n", frameStrings[x]);
		}
		free(frameStrings);
	}
	
}

@end