//
//  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 = nil;
    connectionData = nil;
    
    NSLog(@"Błąd połączenia. Błąd - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

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

    NSLog(@"Zwrócono json: %@", retString);
    
    NSError *parseError = nil;
    NSArray *jsonArray = 
    [NSJSONSerialization JSONObjectWithData:connectionData 
                                    options:0 
                                      error:&parseError];
    
    if (!parseError) {
        [self setMessageArray:jsonArray];
        NSLog(@"Tablica json to: %@", jsonArray);
        [messageTable reloadData];
    } else {
        NSString *err = [parseError localizedDescription];
        NSLog(@"Błąd parsowania: %@", err);
    }
    
    connection = nil;
    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"];
        
        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];
	// Konfiguracja po wczytaniu widoku (zazwyczaj z pliku NIB)
}

- (void)viewDidUnload
{
    [self setMessageTable:nil];
    [self setActivityView:nil];
    [self setActivityIndicator:nil];
    [super viewDidUnload];
    // Zwolnij przechowane podwidoki widoku
    // 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];
    
    //wczytaj komunikaty
    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(@"Nie udało się połączyć...");
        [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
{
    // zwróć YES dla prawidłowych orientacji
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    connectionData = nil;
}

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

@end
