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

#import "ICFNewMessageViewController.h"

@implementation ICFNewMessageViewController
@synthesize nameTextField;
@synthesize messageTextView;
@synthesize connectionData;
@synthesize activityView;
@synthesize activityIndicator;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#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
{
    NSLog(@"Connection completed successfully.");
    
    [connection release], connection = nil;
    [connectionData release], connectionData = nil;
    
    //start activity indicator
    [self.activityView setHidden:YES];
    [self.activityIndicator stopAnimating];

    //Now that connection is complete, OK to return to main view and reload
    [self.presentingViewController dismissViewControllerAnimated:YES
                                                      completion:nil];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [self setNameTextField:nil];
    [self setMessageTextView:nil];
    [self setActivityView:nil];
    [self setActivityIndicator:nil];
    [super viewDidUnload];
}

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

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

- (IBAction)cancelButtonTouched:(id)sender 
{
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (IBAction)saveButtonTouched:(id)sender 
{
    //dismiss keyboard
    [nameTextField resignFirstResponder];
    [messageTextView resignFirstResponder];
    
    //start activity indicator
    [self.activityView setHidden:NO];
    [self.activityIndicator startAnimating];

    //to post json to rails, the new object needs to be in the same format as rails would send back
    //so, we'll create a dictionary for the new message, and wrap that in a dictionary for "message"
    //so that rails will create a message hash with the attributes and values we send.
    
    NSMutableDictionary *messageDictionary = 
    [NSMutableDictionary dictionaryWithCapacity:1];

    [messageDictionary setObject:[nameTextField text] 
                          forKey:@"name"];

    [messageDictionary setObject:[messageTextView text] 
                          forKey:@"message"];

    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = 
    [[NSDateFormatter alloc] init];

    NSString *dateFmt = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
    [dateFormatter setDateFormat:dateFmt];
    [messageDictionary setObject:[dateFormatter stringFromDate:today] 
                          forKey:@"message_date"];

    [dateFormatter release];

    NSDictionary *postDictionary = 
    [NSDictionary dictionaryWithObject:messageDictionary 
                                forKey:@"message"];
    
    NSError *jsonSerializationError = nil;
    NSData *jsonData = [NSJSONSerialization 
                        dataWithJSONObject:postDictionary
                        options:NSJSONWritingPrettyPrinted
                        error:&jsonSerializationError];
    
    if (!jsonSerializationError)
    {
        NSString *serJSON = 
        [[NSString alloc] initWithData:jsonData
                              encoding:NSUTF8StringEncoding];
        
        NSLog(@"serialized json: %@", serJSON);

        NSURL *messageBoardURL = 
        [NSURL URLWithString:kMessageBoardURLString];

        NSMutableURLRequest *request = [NSMutableURLRequest 
                                        requestWithURL:messageBoardURL
                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                            timeoutInterval:30.0];

        [request setHTTPMethod:@"POST"]; // 1
                
        [request setValue:@"application/json" 
        forHTTPHeaderField:@"Accept"]; //2
                
        [request setValue:@"application/json" 
        forHTTPHeaderField:@"Content-Type"]; //2
                
        [request setValue:[NSString stringWithFormat:@"%d", 
        [jsonData length]] forHTTPHeaderField:@"Content-Length"]; //3
                
        [request setHTTPBody: jsonData]; //4

        NSURLConnection *jsonConnection = 
                [[NSURLConnection alloc] initWithRequest:request 
                                                delegate:self];
                
        if (jsonConnection) 
        {
            NSMutableData *connData = [[NSMutableData alloc] init];
            [self setConnectionData:connData];
            [connData release];
        } else 
        {
            NSLog(@"Connection failed...");
        }
                
    } else {
        NSLog(@"JSON Encoding failed: %@",
              [jsonSerializationError localizedDescription]);
    }
    
    //will dismiss this view once the connection has completed, to avoid dealloc'ing
    //this controller and causing a crash (controller losing delegate)
}

#pragma mark - Text Field delegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
    
    //move to the message field
    [messageTextView becomeFirstResponder];
    return YES;
}

@end
