//
//  ViewController.m
//  testIOS
//
//  Created by Nikolai Penkov on 1/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#define kBackGroudQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

#import "ViewController.h"
#import "MsgObj.h"

@implementation ViewController


@synthesize txtDisplayArea;
@synthesize txtIPAddress;
@synthesize btnRunWebService;

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

#pragma mark - View lifecycle

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

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

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

- (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);
}

- (IBAction)runWebServiceAction:(id)sender {
    NSString *ipAddress = [txtIPAddress text];;
    NSString *urlString = [NSString stringWithFormat:@"http://%@:8080/testweb/re/first/tellMe", ipAddress];
    NSLog(@"Call URL: %@", urlString); //3
    NSURL *url = [NSURL URLWithString:urlString];
    dispatch_async(kBackGroudQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: url];
        [self performSelectorOnMainThread:@selector(receiveData:) 
                               withObject:data waitUntilDone:YES];
    });
}

- (void)receiveData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:responseData
                          options:kNilOptions 
                          error:&error];
    MsgObj *msg = [[MsgObj alloc] initWithJSON:json];
    [txtDisplayArea setText:[msg msgTxt]];
}

-(void)dealloc {
    [txtIPAddress release];
    [txtDisplayArea release];
    [btnRunWebService release];
    
    [super dealloc];
}

@end
