//
//  FusionChartsXTiOSDemoViewController.m
//  FusionChartsXTiOSDemo
//
//  Created by FusionCharts.
//

#import "FusionChartsXTiOSDemoViewController.h"
#import "JSONKit.h"

@implementation FusionChartsXTiOSDemoViewController

@synthesize webView;
@synthesize htmlContent;
@synthesize javascriptPath;
@synthesize chartData;
@synthesize chartType;
@synthesize currentOrientation;
@synthesize chartWidth;
@synthesize chartHeight;
@synthesize debugMode;
@synthesize registerWithJavaScript;

@synthesize twitterQuery;
@synthesize twitterData;
@synthesize twitterDataDictionary;
@synthesize twitterDataError;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	// Setting up the Twitter query.
	self.twitterQuery = [NSMutableString stringWithFormat:@"%@", @"http://otter.topsy.com/searchhistogram.json?q=html5&slice=86400&period=7"];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.twitterQuery]];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	// Check whether we have a valid connection.
	if (connection) {
		// Create the NSMutableData to hold the received data.
		self.twitterData = [NSMutableData data];
	} else {
		// Error in receiving data.
		self.twitterDataError = YES;
	}

	// Done using the connection.
	[connection release];
}

- (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;
	self.webView = nil;
}

- (void)dealloc {
	[webView release];
	[htmlContent release];
	[javascriptPath release];
	[chartData release];
	[chartType release];
	[debugMode release];
	[registerWithJavaScript release];
	[twitterQuery release];
	[twitterData release];
	[twitterDataDictionary release];
    [super dealloc];
}

#pragma mark -
#pragma mark Orientation Support

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES since we support all orientations.
    return YES;
}

// Handle interface rotation.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	// Check whether we have valid data.
	if (self.twitterDataError) {
		[self displayDataError];		
	} else {
		// Valid data.
		
		// Store new orientation.
		self.currentOrientation = toInterfaceOrientation;
		
		// Remove existing chart and recreating it
		// as per the new orientation.
		[self removeChart];
		[self createChartData:self.currentOrientation];	
	}
}

#pragma mark -
#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
	
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
	
	// (Re)Initialize the Twitter data store.
    [self.twitterData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Store received data.
    [self.twitterData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// Display an error on connection failure.
	[self displayDataError];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// Convert received JSON data to an Objective-C dictionary.
	self.twitterDataDictionary = [self.twitterData objectFromJSONData];
	
	// Create chart as per current orientation.
	self.currentOrientation = self.interfaceOrientation;
	[self createChartData:self.currentOrientation];
}

#pragma mark -
#pragma mark Chart Setup

- (void)displayDataError 
{
	NSMutableString *displayErrorHTML = [NSMutableString stringWithString:@"<html><head>"];
	[displayErrorHTML appendString:@"<title>Chart Error</title>"];
	[displayErrorHTML appendString:@"</head><body>"];
	[displayErrorHTML appendString:@"<p>Unable to plot chart.<br/>Error receiving data from Twitter.</p>"];
	[displayErrorHTML appendString:@"</body></html>"];
	
	[self.webView loadHTMLString:displayErrorHTML baseURL:nil];
}

- (void)createChartData:(UIInterfaceOrientation)interfaceOrientation
{
	// Check whether we have valid data.
	if (self.twitterDataError) {
		[self displayDataError];
	} else {
		// Valid data.
		
		// Set chart width and height depending on the screen's orientation.
		if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
			self.chartWidth = 300;
			self.chartHeight = 440;
		} else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
			self.chartWidth = 440;
			self.chartHeight = 280;
		}
		
		// Setup chart XML.
		NSDictionary *responseData = [self.twitterDataDictionary objectForKey:@"response"];
		NSArray *histogramData = [responseData objectForKey:@"histogram"];
		self.chartData = [NSMutableString string];
		[self.chartData appendFormat:@"<chart caption='Twitter mentions of HTML5' subCaption='In the last 7 days' showValues='0'>"];
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setDateStyle:NSDateFormatterShortStyle];
		for (int i = 0; i < [histogramData count]; i++) {
			[self.chartData appendFormat:@"<set label='%@' value='%@' />", [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:-(i+1)*86400]], [histogramData objectAtIndex:i]];
		}
		[self.chartData appendFormat:@"</chart>"];
		[dateFormatter release];
		
		// Setup chart HTML.
		self.htmlContent = [NSMutableString stringWithFormat:@"%@", @"<html><head>"];
		[self.htmlContent appendString:@"<script type='text/javascript' src='FusionCharts.js'></script>"];
		[self.htmlContent appendString:@"</head><body><div id='chart_container'>Chart will render here.</div>"];
		[self.htmlContent appendString:@"<script type='text/javascript'>"];
		[self.htmlContent appendFormat:@"var chart_object = new FusionCharts('Column3D.swf', 'twitter_data_chart', '%f', '%f', '0', '1');", self.chartWidth, self.chartHeight];
		[self.htmlContent appendFormat:@"chart_object.setXMLData(\"%@\");", self.chartData];
		[self.htmlContent appendString:@"chart_object.render('chart_container');"];
		[self.htmlContent appendString:@"</script></body></html>"];
		
		// Draw the actual chart.
		[self plotChart];
	}
}

- (void)plotChart
{
	NSURL *baseURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", [[NSBundle mainBundle] bundlePath]]];
	[self.webView loadHTMLString:self.htmlContent baseURL:baseURL];
}

- (void)removeChart
{
	NSString *emptyChartContainer = [NSString stringWithString:@"<script type='text/javascript'>document.getElementById('chart_container').innerHTML='';</script>"];
	[self.webView stringByEvaluatingJavaScriptFromString:emptyChartContainer]; 
}

@end
