//
//  InAppMailerViewController.m
//  InAppMailer
//
//  Created by Chris Adamson on 7/9/09.
//  Copyright Subsequently and Furthermore, Inc. 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//


#import "InAppMailerViewController.h"

@implementation InAppMailerViewController

@synthesize mailHistoryView;

#pragma mark button event handler

//START:code.InAppMailerViewController.composemailtapped
-(IBAction) composeMailTapped {
	if (! [MFMailComposeViewController canSendMail]) {
		UIAlertView *cantMailAlert = [[UIAlertView alloc]
			initWithTitle:@"Can't mail"
			message:@"This device is not able to send e-mail"
			delegate:NULL
			cancelButtonTitle:@"OK"
			otherButtonTitles:NULL];
		[cantMailAlert show];
		[cantMailAlert release];
		return;
	}
	
	MFMailComposeViewController *mailController =
		[[MFMailComposeViewController alloc] init];
	[mailController setMessageBody:@"My app can send mail" isHTML:NO];
	mailController.mailComposeDelegate = self;
	[self presentModalViewController:mailController animated:YES];
}
//END:code.InAppMailerViewController.composemailtapped

#pragma mark delegate method

//START:code.InAppMailerViewController.mailcomposecontrollerdidfinishwithresult
- (void)mailComposeController:(MFMailComposeViewController*)controller
		didFinishWithResult:(MFMailComposeResult)result
		error:(NSError*)error {
	if (error) {
		UIAlertView *cantMailAlert = [[UIAlertView alloc]
			  initWithTitle:@"Mail error"
			  message: [error localizedDescription]
			  delegate:NULL
			  cancelButtonTitle:@"OK"
			  otherButtonTitles:NULL];
		[cantMailAlert show];
		[cantMailAlert release];
	} 
	NSString *resultString;
	switch (result) {
		case MFMailComposeResultSent:
			resultString = @"Sent mail"; break;
		case MFMailComposeResultSaved:
			resultString = @"Saved mail"; break;
		case MFMailComposeResultCancelled:
			resultString = @"Cancelled mail"; break;
		case MFMailComposeResultFailed:
			resultString = @"Mail failed"; break;
	}
	mailHistoryView.text = [NSString stringWithFormat:
		@"%@%@ at %@\n", mailHistoryView.text,
		resultString, [NSDate date]];
	[controller dismissModalViewControllerAnimated:YES];
	[controller release];
}
//END:code.InAppMailerViewController.mailcomposecontrollerdidfinishwithresult


#pragma mark vc lifecycle

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[mailHistoryView release];
}

@end
