//
//  RadioParser.m
//  Allzic
//
//  Created by Alia Bourouis on 26/03/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "RadioParser.h"
#import "AppDelegate.h"

@implementation RadioParser

@synthesize isParseError,radioArray;

- (id)init {
	
    self = [super init];
    if (self != nil) {
        // Initialization code.
		appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        radioArray = [[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];
    NSMutableArray *tempRadioArray = [stringRecup JSONValue];
    
    //on ne trie pas les resultat pour l'onglet Decouvrir des radios
    if ([self isEqual:appDelegate.dataController.randomRadiosParser]) {
        radioArray = [NSArray arrayWithArray:tempRadioArray];
    }
    //on trie les resultats par ordre alphabetique
    else if ([self isEqual:appDelegate.dataController.categoriesParser] || [self isEqual:appDelegate.dataController.categoriesRadiosParser] || [self isEqual:appDelegate.dataController.aroundMeRadiosParser]) {
        radioArray = [tempRadioArray sortedArrayUsingComparator:^(id obj1, id obj2) {
            return [[obj1 objectForKey:@"title"] compare:[obj2 objectForKey:@"title"]];
        }];
    }
    //on trie les resultats par id
    else {
        radioArray = [tempRadioArray sortedArrayUsingComparator:^(id obj1, id obj2) {
            return [[NSNumber numberWithInt:[[obj1 objectForKey:@"hierarchy"] intValue]] compare:[NSNumber numberWithInt:[[obj2 objectForKey:@"hierarchy"] intValue]]];
        }];
    }
    [appDelegate.dataController parseFinished:self];
}

@end
