//
//  SimpleTwitterClientViewController.m
//  SimpleTwitterClient
//
//  Created by Chris Adamson on 4/17/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 "SimpleTwitterClientViewController.h"

//START:code.SimpleTwitterClientViewController.defineinterestingtagnames
#define INTERESTING_TAG_NAMES @"text", @"name", nil
//END:code.SimpleTwitterClientViewController.defineinterestingtagnames

/* for information on Twitter's XML API for the friends timeline, see
 http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-public_timeline
 */


@implementation SimpleTwitterClientViewController

@synthesize tweetsView, activityIndicator;


//START:code.SimpleTwitterClientViewController.updateTweets
-(IBAction) updateTweets {
	tweetsView.text = @"";
	[tweetsData release];
	tweetsData = [[NSMutableData alloc] init];
	NSURL *url = [NSURL URLWithString:
		@"http://twitter.com/statuses/public_timeline.xml"];
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
	NSURLConnection *connection = [[NSURLConnection alloc]
			   initWithRequest:request
			   delegate:self];
	[connection release];
	[request release];
	[activityIndicator startAnimating];
}
//END:code.SimpleTwitterClientViewController.updateTweets

//START:code.SimpleTwitterClientViewController.startparsingtweets
- (void) startParsingTweets {
	NSXMLParser *tweetParser = [[NSXMLParser alloc] initWithData:tweetsData];
	tweetParser.delegate = self;
	[tweetParser parse];
	[tweetParser release];
}
//END:code.SimpleTwitterClientViewController.startparsingtweets

#pragma mark UIViewController methods

//START:code.SimpleTwitterClientViewController.viewdidload
- (void) viewDidLoad {
	[super viewDidLoad];
	interestingTags = [[NSSet alloc] initWithObjects: INTERESTING_TAG_NAMES];
}
//END:code.SimpleTwitterClientViewController.viewdidload

#pragma mark NSURLConnection callbacks

//START:code.SimpleTwitterClientViewController.connectiondidreceivedata
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[tweetsData appendData: data];
}
//END:code.SimpleTwitterClientViewController.connectiondidreceivedata

-(void) connection:(NSURLConnection *)connection
  didFailWithError: (NSError *)error {
	UIAlertView *errorAlert = [[UIAlertView alloc]
				   initWithTitle: [error localizedDescription]
				   message: [error localizedFailureReason]
				   delegate:nil
				   cancelButtonTitle:@"OK"
				   otherButtonTitles:nil];
	[errorAlert show];
	[errorAlert release];
	[activityIndicator stopAnimating];
}

//START:code.SimpleTwitterClientViewController.connectiondidfinishloading
- (void) connectionDidFinishLoading: (NSURLConnection*) connection {
	[activityIndicator stopAnimating];
	[self startParsingTweets];
}
//END:code.SimpleTwitterClientViewController.connectiondidfinishloading



#pragma mark NSXMLParser callbacks

//START:code.SimpleTwitterClientViewController.parserdidstartdocument
- (void)parserDidStartDocument:(NSXMLParser *)parser {
	[tweetsString release];
	tweetsString = [[NSMutableString alloc]
			initWithCapacity: (20 * (140 + 20)) ];
	currentElementName = nil;
	currentText = nil;
}
//END:code.SimpleTwitterClientViewController.parserdidstartdocument


//START:code.SimpleTwitterClientViewController.parserdidstartelement
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
		namespaceURI:(NSString *)namespaceURI
		qualifiedName:(NSString *)qualifiedName
		attributes:(NSDictionary *)attributeDict {
	if ([elementName isEqualToString:@"status"]) {
		[currentTweetDict release];
		currentTweetDict = [[NSMutableDictionary alloc]
			initWithCapacity: [interestingTags count]];
	}
	else if ([interestingTags containsObject: elementName]) { //<label id="code.SimpleTwitterClient.SimpleTwitterClientViewController.didstartelement.setcontainsobject"/>
		currentElementName = elementName;
		currentText = [[NSMutableString alloc] init];
	}
 }
//END:code.SimpleTwitterClientViewController.parserdidstartelement

//START:code.SimpleTwitterClientViewController.parserdidendelement
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
		namespaceURI:(NSString *)namespaceURI
		qualifiedName:(NSString *)qName {
	if ([elementName isEqualToString:currentElementName]) {
		[currentTweetDict setValue: currentText forKey: currentElementName];
	} else if ([elementName isEqualToString:@"status"]) {
		[tweetsString appendFormat:@"%@: %@\n\n",
			[currentTweetDict valueForKey:@"name"],
			[currentTweetDict valueForKey:@"text"]];
	}
	[currentText release];
	currentText = nil;
}
//END:code.SimpleTwitterClientViewController.parserdidendelement

//START:code.SimpleTwitterClientViewController.parserfoundcharacters
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	[currentText appendString:string];
}
//END:code.SimpleTwitterClientViewController.parserfoundcharacters

//START:code.SimpleTwitterClientViewController.parserdidenddocument
- (void)parserDidEndDocument:(NSXMLParser *)parser {
	tweetsView.text = tweetsString;
}
//END:code.SimpleTwitterClientViewController.parserdidenddocument

// TODO: add http authentication for friends timeline

#pragma mark -
#pragma mark ViewController boilerplate


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
	[tweetsView release];
	[activityIndicator release];
	[interestingTags release];
}


@end
