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

#import "DataController.h"

#import "AppDelegate.h"

static DataController *sharedInstance;

@implementation DataController

@synthesize userPreferences,allzicRadiosParser,categoriesParser,categoriesRadiosParser,countryRadiosParser,departmentRadiosParser,cityListParser,cityRadiosParser,aroundMeRadiosParser,randomRadiosParser,topRadiosParser,playlistParser,searchParser,adswizzParser,updateAndRatingParser,lastRadioArray,currentRadioArray,currentRadioIndex,favoriteRadioArray,favoriteCategoryArray,currentAccuracy;


+ (DataController *)sharedInstance {
	
    if(sharedInstance == nil)
        sharedInstance = [[DataController alloc] init];
    return sharedInstance;
}

- (id)init {
	
    self = [super init];
    if (self != nil) {
        // Initialization code.
		appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        userPreferences = [NSUserDefaults standardUserDefaults];
        
        //recuperation en memoire des Dernieres radios ecoutees
        NSData *lastRadioData = [self.userPreferences objectForKey:@"lastRadioArray"];
        if (lastRadioData != nil) {
            lastRadioArray = [NSKeyedUnarchiver unarchiveObjectWithData:lastRadioData];
        } else {
            lastRadioArray = [[NSMutableArray alloc] init];
        }
        
        //recuperation en memoire des Radios favorites
        NSData *favoriteRadioData = [self.userPreferences objectForKey:@"favoriteRadioArray"];
        if (favoriteRadioData != nil) {
            favoriteRadioArray = [NSKeyedUnarchiver unarchiveObjectWithData:favoriteRadioData];
        } else {
            favoriteRadioArray = [[NSMutableArray alloc] init];
        }
        
        //recuperation en memoire des Categories favorites
        NSData *favoriteCategoryData = [self.userPreferences objectForKey:@"favoriteCategoryArray"];
        if (favoriteCategoryData != nil) {
            favoriteCategoryArray = [NSKeyedUnarchiver unarchiveObjectWithData:favoriteCategoryData];
        } else {
            favoriteCategoryArray = [[NSMutableArray alloc] init];
        }
        
        locationController = [[CLLocationManager alloc]init];
		locationController.delegate	= self;
        currentAccuracy = 0;
    }
    return self;
}

- (void)initParsers {
    
    [appDelegate.allzicVC refreshTableWithData:nil];
    [self parseAllzicRadios];
    [self parseCategories];
    [self parseUpdateAndRating];
}

- (void)parseAllzicRadios {
    
    [appDelegate.allzicVC.noResultTableLabel setHidden:YES];
    [appDelegate.allzicVC.loadingTableView setHidden:NO];
    allzicRadiosParser = [[RadioParser alloc] init];
    [allzicRadiosParser httpConnection:@"http://www.allzicradio.com/json/get_all/1"];
}

- (void)parseCategories {
    
    [appDelegate.categoriesVC.noResultTableLabel setHidden:YES];
    [appDelegate.categoriesVC.loadingTableView setHidden:NO];
    categoriesParser = [[RadioParser alloc] init];
    [categoriesParser httpConnection:@"http://www.allzicradio.com/json/get_categories"];
}

- (void)parseRadiosWithCategory:(int)categoryId {
    
    [appDelegate.categoriesRadiosVC.noResultTableLabel setHidden:YES];
    [appDelegate.categoriesRadiosVC.loadingTableView setHidden:NO];
    categoriesRadiosParser = [[RadioParser alloc] init];
    [categoriesRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_categories/%d",categoryId]];
}

- (void)parseCountries {
    
    [appDelegate.countryListVC.noResultTableLabel setHidden:YES];
    [appDelegate.countryListVC.loadingTableView setHidden:NO];
    countryRadiosParser = [[RadioParser alloc] init];
    [countryRadiosParser httpConnection:@"http://www.allzicradio.com/json/get_countries"];
}

- (void)parseRadiosWithCountry:(NSString *)countryId {
    
    [appDelegate.categoriesRadiosVC.noResultTableLabel setHidden:YES];
    [appDelegate.categoriesRadiosVC.loadingTableView setHidden:NO];
    categoriesRadiosParser = [[RadioParser alloc] init];
    [categoriesRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_country/%@/0/10000",countryId]];
}

- (void)parseNationalRadios {
    
    [appDelegate.categoriesRadiosVC.noResultTableLabel setHidden:YES];
    [appDelegate.categoriesRadiosVC.loadingTableView setHidden:NO];
    categoriesRadiosParser = [[RadioParser alloc] init];
    [categoriesRadiosParser httpConnection:@"http://www.allzicradio.com/fr/json/get_all/0/page/50/nationale"];
}

- (void)parseDepartmentsWithCountry:(NSString *)countryId {
    
    [appDelegate.departmentListVC.noResultTableLabel setHidden:YES];
    [appDelegate.departmentListVC.loadingTableView setHidden:NO];
    departmentRadiosParser = [[RadioParser alloc] init];
    [departmentRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_departments/%@",countryId]];
}

- (void)parseRadiosWithDepartment:(NSString *)department {
    
    [appDelegate.categoriesRadiosVC.noResultTableLabel setHidden:YES];
    [appDelegate.categoriesRadiosVC.loadingTableView setHidden:NO];
    categoriesRadiosParser = [[RadioParser alloc] init];
    [categoriesRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_department/%@/%@/0/10000",@"FR",department]];
}

- (void)parseCitiesWithCountry:(NSString *)countryId {
    
    cityListParser = [[RadioParser alloc] init];
    [cityListParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_cities/%@",countryId]];
}

- (void)parseRadiosWithCity:(NSString *)city fromCountry:(NSString *)countryId {
    
    [appDelegate.cityRadiosVC.noResultTableLabel setHidden:YES];
    [appDelegate.cityRadiosVC.loadingTableView setHidden:NO];
    cityRadiosParser = [[RadioParser alloc] init];
    [cityRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_city/%@/%@/0/10000",countryId,city]];
}

- (void)parseLocationRadiosWithAccuracy:(int)accuracyType {
    
    currentAccuracy = accuracyType;
    [locationController startUpdatingLocation];
}

- (void)parseAroundMeRadios {
    
    [appDelegate.aroundMeRadioVC.noResultTableLabel setHidden:YES];
    if (geoParser.dataArray != nil && geoParser.dataArray.count > 0) {
        [appDelegate.aroundMeRadioVC.loadingTableView setHidden:NO];
        aroundMeRadiosParser = [[RadioParser alloc] init];
        switch (currentAccuracy) {
                //commune
            case 0: {
                NSString *zipcode = [[geoParser.dataArray objectAtIndex:0] objectForKey:@"postalCode"];
                if (zipcode != nil && zipcode.length > 2) {
                    if ([[zipcode substringToIndex:2] isEqualToString:@"75"] || [[zipcode substringToIndex:2] isEqualToString:@"92"] || [[zipcode substringToIndex:2] isEqualToString:@"93"] || [[zipcode substringToIndex:2] isEqualToString:@"94"] || [[zipcode substringToIndex:2] isEqualToString:@"69"] || [[zipcode substringToIndex:2] isEqualToString:@"13"]) {
                        zipcode = [NSString stringWithFormat:@"%@000",[zipcode substringToIndex:2]];
                    }
                }
                [aroundMeRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_zipcode/%@/%@/0/10000",[[geoParser.dataArray objectAtIndex:0] objectForKey:@"countryCode"],zipcode]];
            }
                break;
                //departement
            case 1: {
                NSString *dept = [[geoParser.dataArray objectAtIndex:0] objectForKey:@"postalCode"];
                if (dept != nil && dept.length > 2) {
                    if ([[dept substringToIndex:2] intValue] >= 97) {
                        dept = [dept substringToIndex:3];
                    }
                    else {
                        dept = [dept substringToIndex:2];
                    }
                }
                [aroundMeRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_department/%@/%@/0/10000",[[geoParser.dataArray objectAtIndex:0] objectForKey:@"countryCode"],dept]];
            }
                break;
                //pays
            case 2: {
                [aroundMeRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_radios_by_country/%@/0/10000",[[geoParser.dataArray objectAtIndex:0] objectForKey:@"countryCode"]]];
            }
                break;
            default:
                break;
        }
    } else {
        NSLog(@"> > > Aucun retour de GeonamesParser");
    }
}

- (void)parseRandomRadios {
    
    [appDelegate.randomRadioVC.noResultTableLabel setHidden:YES];
    [appDelegate.randomRadioVC.loadingTableView setHidden:NO];
    randomRadiosParser = [[RadioParser alloc] init];
    NSString *favoriteString = @"";
    for (int i=0; i<favoriteRadioArray.count; i++) {
        favoriteString = [NSString stringWithFormat:@"%@%@-",favoriteString,[[favoriteRadioArray objectAtIndex:i] objectForKey:@"id"]];
    }
    if (favoriteString.length > 0) {
        favoriteString = [favoriteString substringToIndex:(favoriteString.length - 1)];
    }
    [randomRadiosParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/get_suggest/%@",favoriteString]];
}

- (void)parseTopRadios {
    
    [appDelegate.topRadioVC.noResultTableLabel setHidden:YES];
    [appDelegate.topRadioVC.loadingTableView setHidden:NO];
    topRadiosParser = [[RadioParser alloc] init];
    [topRadiosParser httpConnection:@"http://www.allzicradio.com/json/get_top"];
}

- (void)parsePlaylist {
    
    playlistParser = [[RadioParser alloc] init];
    [playlistParser httpConnection:[[self.currentRadioArray objectAtIndex:self.currentRadioIndex] objectForKey:@"playlist"]];
}

- (void)parseResultWithSearch:(NSString *)searchText {
    
    [appDelegate.searchVC.noResultTableLabel setHidden:YES];
    [appDelegate.searchVC.loadingTableView setHidden:NO];
    NSString *encodedString = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    searchParser = [[RadioParser alloc] init];
    [searchParser httpConnection:[NSString stringWithFormat:@"http://www.allzicradio.com/json/autocomplete/%@",encodedString]];
}

- (void)parseFinished:(id)parserController {
    
    if ([parserController isEqual:allzicRadiosParser]) {
        [appDelegate refreshAllzicVC];
    } else if ([parserController isEqual:categoriesParser]) {
        [appDelegate refreshCategoriesVC];
    } else if ([parserController isEqual:categoriesRadiosParser]) {
        [appDelegate refreshCategoriesRadiosVC];
    } else if ([parserController isEqual:countryRadiosParser]) {
        [appDelegate refreshCountryListVC];
    } else if ([parserController isEqual:departmentRadiosParser]) {
        [appDelegate refreshDepartmentListVC];
    } else if ([parserController isEqual:cityListParser]) {
        [appDelegate refreshCityListVC];
    } else if ([parserController isEqual:cityRadiosParser]) {
        [appDelegate refreshCityRadiosVC];
    } else if ([parserController isEqual:playlistParser]) {
        [appDelegate refreshPlayerVC];
    } else if ([parserController isEqual:randomRadiosParser]) {
        [appDelegate refreshRandomRadioVC];
    } else if ([parserController isEqual:topRadiosParser]) {
        [appDelegate refreshTopRadioVC];
    } else if ([parserController isEqual:searchParser]) {
        [appDelegate refreshSearchVC];
    } else if ([parserController isEqual:geoParser]) {
        [self parseAroundMeRadios];
    } else if ([parserController isEqual:aroundMeRadiosParser]) {
        [appDelegate refreshAroudMeVC];
    } else if ([parserController isEqual:adswizzParser]) {
        [appDelegate refreshPlayerAd];
    } else if ([parserController isEqual:updateAndRatingParser]) {
        [appDelegate refreshUpdateAndRating];
    }
}

- (void)setCurrentRadioArray:(NSArray *)radios andCurrentRadioIndex:(int)index {
    
    self.currentRadioArray = radios;
    self.currentRadioIndex = index;
    NSDictionary *currentRadio = [radios objectAtIndex:index];
    
    //maj de la liste des 20 dernieres radio ecoutees (sauf si on parcourt justement la liste des ecoutes recentes)
    if (![appDelegate.oldVC isEqual:appDelegate.lastRadiosVC]) {
        int existingIndex = -1;
        for (int i=0; i<self.lastRadioArray.count; i++) {
            if ([[[self.lastRadioArray objectAtIndex:i] objectForKey:@"id"] intValue] == [[currentRadio objectForKey:@"id"] intValue]) {
                existingIndex = i;
            }
        }
        if (existingIndex >= 0) {
            [self.lastRadioArray removeObjectAtIndex:existingIndex];
        } else if (self.lastRadioArray.count > 20) {
            [self.lastRadioArray removeLastObject];
        }
        [self.lastRadioArray insertObject:currentRadio atIndex:0];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:lastRadioArray];
        [self.userPreferences setValue:data forKey:@"lastRadioArray"];
        [self.userPreferences synchronize];
    }
}

- (void)addFavoriteRadio:(NSDictionary *)radio {
    
    [self removeFavoriteRadioWithId:[radio objectForKey:@"id"]];
    [self.favoriteRadioArray addObject:radio];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.favoriteRadioArray];
    [self.userPreferences setValue:data forKey:@"favoriteRadioArray"];
    [self.userPreferences synchronize];
}

- (void)removeFavoriteRadioWithId:(NSString *)radioId {
    
    int existingIndex = -1;
    for (int i=0; i<self.favoriteRadioArray.count; i++) {
        if ([[[self.favoriteRadioArray objectAtIndex:i] objectForKey:@"id"] intValue] == [radioId intValue]) {
            existingIndex = i;
        }
    }
    if (existingIndex >= 0) {
        [self.favoriteRadioArray removeObjectAtIndex:existingIndex];
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.favoriteRadioArray];
    [self.userPreferences setValue:data forKey:@"favoriteRadioArray"];
    [self.userPreferences synchronize];
}

- (BOOL)isFavoriteRadioWithId:(NSString *)radioId {
    
    BOOL isFavorite = NO;
    int existingIndex = -1;
    for (int i=0; i<self.favoriteRadioArray.count; i++) {
        if ([[[self.favoriteRadioArray objectAtIndex:i] objectForKey:@"id"] intValue] == [radioId intValue]) {
            existingIndex = i;
        }
    }
    if (existingIndex >= 0) {
        isFavorite = YES;
    }
    return isFavorite;
}

- (void)addFavoriteCategory:(NSDictionary *)category {
    
    [self removeFavoriteCategoryWithId:[category objectForKey:@"id"]];
    [self.favoriteCategoryArray addObject:category];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:favoriteCategoryArray];
    [self.userPreferences setValue:data forKey:@"favoriteCategoryArray"];
    [self.userPreferences synchronize];
}

- (void)removeFavoriteCategoryWithId:(NSString *)categoryId {
    
    int existingIndex = -1;
    for (int i=0; i<self.favoriteCategoryArray.count; i++) {
        if ([[[self.favoriteCategoryArray objectAtIndex:i] objectForKey:@"id"] intValue] == [categoryId intValue]) {
            existingIndex = i;
        }
    }
    if (existingIndex >= 0) {
        [self.favoriteCategoryArray removeObjectAtIndex:existingIndex];
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.favoriteCategoryArray];
    [self.userPreferences setValue:data forKey:@"favoriteCategoryArray"];
    [self.userPreferences synchronize];
}

- (BOOL)isFavoriteCategoryWithId:(NSString *)categoryId {
    
    BOOL isFavorite = NO;
    int existingIndex = -1;
    for (int i=0; i<self.favoriteCategoryArray.count; i++) {
        if ([[[self.favoriteCategoryArray objectAtIndex:i] objectForKey:@"id"] intValue] == [categoryId intValue]) {
            existingIndex = i;
        }
    }
    if (existingIndex >= 0) {
        isFavorite = YES;
    }
    return isFavorite;
}

- (void)getGeonames {
    
    geoParser = [[GeonamesParser alloc] init];
    [geoParser httpConnection:[NSString stringWithFormat:@"http://api.geonames.org/findNearbyPostalCodesJSON?lat=%f&lng=%f&username=egdigital_ios&maxRows=3",latitude,longitude]];
}

- (void)parseAdswizz {
    
    adswizzParser = [[AdswizzParser alloc] init];
    //[adswizzParser httpConnection:@"http://deliveryengine.espacegroup.adswizz.com/swfIndex?reqType=AdsSetup&protocolVersion=2.0&zoneId=113&companionZones=114"];
    [adswizzParser httpConnection:@"http://deliveryengine.espacegroup.adswizz.com/swfIndex?reqType=AdsSetup&protocolVersion=2.0&zoneId=113&companionZones=114;115"];
}

- (void)parseUpdateAndRating {
    
    updateAndRatingParser = [[RadioParser alloc] init];
    [updateAndRatingParser httpConnection:@"http://www.allzicradio.com/fr/json/get_notices/ios"];
}

//----------------------------------------
//		CLLocationManager Delegate
//----------------------------------------

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation; {
	
    gpsEnable = YES;
	CLLocationCoordinate2D newCoord = [newLocation coordinate];
	latitude	= newCoord.latitude;
	longitude	= newCoord.longitude;
	NSLog(@"update location : %f(lat) %f(lon)", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
	[locationController stopUpdatingLocation];
    [self getGeonames];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	
	NSLog(@"LOCATION MANAGER DID FAIL WITH ERROR : %@",error);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:@"Pour utiliser cette fonctionnalité vous devez autoriser l'accès aux données de localisation dans Réglages"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    gpsEnable = NO;
}

@end










