//
//  ICFViewController.m
//  MessageBoard
//
//  Created by Joe Keeley on 3/29/12.
//  Copyright (c) 2012 Explore Systems, Inc. All rights reserved.
//

#import "ICFViewController.h"
#import "ICFNewMessageViewController.h"

@implementation ICFViewController

@synthesize connectionData;
@synthesize messageArray;
@synthesize messageTable;
@synthesize activityView;
@synthesize activityIndicator;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - NSURLConnection delegate methods

- (void)connection:(NSURLConnection *)connection 
didReceiveResponse:(NSURLResponse *)response
{
    [self.connectionData setLength:0];
}

- (void)connection:(NSURLConnection *)connection 
    didReceiveData:(NSData *)data
{
    [self.connectionData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    [connection release], connection = nil;
    [connectionData release], connectionData = nil;
    
    NSLog(@"Connection failed. Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *retString = 
    [NSString stringWithUTF8String:[connectionData bytes]];

    NSLog(@"json returned: %@", retString);
    
    NSError *parseError = nil;
    NSArray *jsonArray = 
    [NSJSONSerialization JSONObjectWithData:connectionData 
                                    options:0 
                                      error:&parseError];
    
    if (!parseError) {
        [self setMessageArray:jsonArray];
        NSLog(@"json array is %@", jsonArray);
        [messageTable reloadData];
    } else {
        NSString *err = [parseError localizedDescription];
        NSLog(@"Encountered error parsing: %@", err);
    }
    
    [connection release], connection = nil;
    [connectionData release], connectionData = nil;
    
    [self.activityView setHidden:YES];
    [self.activityIndicator stopAnimating];
}

#pragma mark - Table data source 

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleSubtitle
                 reuseIdentifier:@"MsgCell"] autorelease];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary *message = 
    (NSDictionary *)[[self.messageArray 
                      objectAtIndex:indexPath.row]
                       objectForKey:@"message"];
    
    NSString *byLabel = 
    [NSString stringWithFormat:@"by %@ on %@",
     [message objectForKey:@"name"],
     [message objectForKey:@"message_date"]];
    
    cell.textLabel.text = [message objectForKey:@"message"];
    cell.detailTextLabel.text = byLabel;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    return [[self messageArray] count];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [self setMessageTable:nil];
    [self setActivityView:nil];
    [self setActivityIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear, refreshing messages");
    //start activity indicator
    [self.activityView setHidden:NO];
    [self.activityIndicator startAnimating];
    
    //load messages
    NSURL *msgURL = [NSURL URLWithString:kMessageBoardURLString];
    NSURLRequest *msgRequest = 
    [NSURLRequest requestWithURL:msgURL
                 cachePolicy:NSURLRequestUseProtocolCachePolicy
             timeoutInterval:60.0];

    NSURLConnection *theConnection = 
    [[NSURLConnection alloc] initWithRequest:msgRequest 
                                delegate:self];

    if (theConnection) {
        NSMutableData *connData = [[NSMutableData alloc] init];
        [self setConnectionData:connData];
    } else {
        NSLog(@"Connection failed...");
        [self.activityView setHidden:YES];
        [self.activityIndicator stopAnimating];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    [messageTable release];
    [activityView release];
    [activityIndicator release];
    [connectionData release], connectionData = nil;
    [super dealloc];
}

- (IBAction)newMessageTouched:(id)sender 
{
    ICFNewMessageViewController *controller = [[ICFNewMessageViewController alloc] init];
    [self presentViewController:controller
                       animated:YES
                     completion:nil];
    [controller release];
}

@end
