//
//  GeonamesParser.m
//  Allzic
//
//  Created by Alia Bourouis on 28/04/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "GeonamesParser.h"
#import "AppDelegate.h"

@implementation GeonamesParser

@synthesize isParseError,dataArray;

- (id)init {
	
    self = [super init];
    if (self != nil) {
        // Initialization code.
		appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        dataArray = [[NSMutableArray alloc] init];
    }
    return self;
}


//-----------------------------------------
//		NSURLConnection Delegate
//-----------------------------------------

- (void)httpConnection:(NSString *)url {
	
    isParseError = NO;
    if(!url) {
        url = @"";
    }
    NSLog(@"HTTP CONNECTION TO URL : %@",url);
	NSURLCache *sharedCache = [NSURLCache sharedURLCache];
	[sharedCache removeAllCachedResponses];
	
	NSMutableURLRequest *serverRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:40.0];
	[serverRequest setValue:@"no-store, no-cache, must-revalidate, post-check=0, pre-check=0" forHTTPHeaderField:@"Cache-Control"];
	[serverRequest addValue:@"no-cache" forHTTPHeaderField:@"Pragma"];
	serverConnection = nil;
	serverConnection = [[NSURLConnection alloc] initWithRequest:serverRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
	receivedData = nil;
    receivedData = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	if(data != nil) {
		if(receivedData == nil) receivedData = [[NSMutableData alloc]init];
		[receivedData appendData:data];
	}
	else {
		NSLog(@"data is nil");
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	parsedData = [[NSData alloc] initWithData:receivedData];
	[self parseData:parsedData];
	if(receivedData != nil) receivedData = nil;
	if(serverConnection != nil) serverConnection = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	NSLog(@"Connection failed with error : %@",error);
	if(receivedData != nil) receivedData = nil;
	if(serverConnection != nil) serverConnection = nil;
    isParseError = YES;
    [appDelegate.dataController parseFinished:self];
}

-(void)parseData:(NSData *)data {
    
    NSString *stringRecup =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [stringRecup JSONValue];
    if ([dic objectForKey:@"postalCodes"] != nil) {
        dataArray = [dic objectForKey:@"postalCodes"];
    }
    [appDelegate.dataController parseFinished:self];
}

@end





