//
//  AgenceAppDelegate.m
//  Agence
//
//  Created by Olivier Savard on 11-01-19.
//  Copyright 2011 OSInfo Informatique. All rights reserved.
//

#import "AgenceAppDelegate.h"
#import "ListeViewController.h"
#import "XMLParser.h"
#import "ListeViewController.h"
#import "Immeuble.h"

#define	kFileName @"archive"
#define kDataKey  @"DataFavoris"
#define kDataKey2 @"DataMenu"

@implementation AgenceAppDelegate

@synthesize window;
@synthesize	tabBarController;
@synthesize navController;
@synthesize list;
@synthesize lastIndexPathFiltre;
@synthesize montantMin;
@synthesize montantMax;
@synthesize reload;
@synthesize reInit;
@synthesize listeFavoris;
@synthesize countFavoris;
@synthesize tabBarItem;
@synthesize locationManager;
@synthesize locationCentre;
@synthesize success;
@synthesize splashView;
@synthesize imagesCacheSmall;
@synthesize imagesCacheLarge;

#pragma mark -
#pragma mark Application lifecycle

-(void)parseXML{
	// Override point for customization after application launch.
	NSURL *url = [[NSURL alloc] initWithString:@"http://www.web-k.org/os/immeubles.xml"];
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
	
	//Initialize the delegate.
	XMLParser *parser = [[XMLParser alloc] initXMLParser];
	
	//Set delegate
	[xmlParser setDelegate:parser];
	
	//Start parsing the XML file.
	success = [xmlParser parse];
	
	if(success)
		NSLog(@"No Errors");
	else
		NSLog(@"Error Error Error!!!");	
}



-(BOOL)isFavorite:(Immeuble *)unImmeuble{
	BOOL isFavorite = NO;
	for (int j=0; j < [listeFavoris count]; j++) {
		Immeuble *unImmeubleFav = [[Immeuble alloc]init];
		unImmeubleFav = [listeFavoris objectAtIndex:j];
		NSLog(@"isFavorite: Unimmeuble.id %i",unImmeuble.immeubleID);
		NSLog(@"isFavorite: UnimmeubleFav.id %i",unImmeubleFav.immeubleID);
		if (unImmeuble.immeubleID == unImmeubleFav.immeubleID)
		{
			NSLog(@"PAREIL!!");
			isFavorite = YES;
		}
	}
	return isFavorite;
}

-(void)reconstructFav{
	NSLog(@"Reconstruct Favorites");
	NSMutableArray *newArray = [[NSMutableArray alloc]init];
	for (int i=0; i < [list count]; i++){
		NSLog(@"MILLIEU..");
		Immeuble *unImmeubleMain = [[Immeuble alloc]init];
		unImmeubleMain = [list objectAtIndex:i];
		if([self isFavorite:unImmeubleMain])
			[newArray addObject:unImmeubleMain];
	}
	self.listeFavoris = nil;
	self.listeFavoris = newArray;
	[newArray release];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
	NSLog(@"App did finish launching");
	
	//initialisation des dictionnaires d'images
	imagesCacheSmall = [[NSMutableDictionary alloc]init];
	imagesCacheLarge = [[NSMutableDictionary alloc]init];
	
	//******************LOADER LES SAUVEGARDES*********************************
	if ([self dataFilePath] != nil) {
		NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
		NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
		NSMutableArray *array = [[NSMutableArray alloc]init];
		array = [unarchiver decodeObjectForKey:kDataKey];
		listeFavoris = array;
		
		
		//les view controllers de tabbar
		NSArray *savedOrder = [unarchiver decodeObjectForKey:kDataKey2];
		NSMutableArray *orderedTabs = [NSMutableArray arrayWithCapacity:[tabBarController.viewControllers count]];
		
		if ([savedOrder count] > 0 ) {
			for (int i = 0; i < [savedOrder count]; i++){
				for (UIViewController *aController in tabBarController.viewControllers) {
					NSLog(@"LOAD..Title: %@",aController.title);
					if ([aController.title isEqualToString:[savedOrder objectAtIndex:i]]) {
						[orderedTabs addObject:aController];
					}
				}
			}
			tabBarController.viewControllers = orderedTabs;
		}
		
		[unarchiver finishDecoding];
		
		[array release];
		
		//[unarchiver release];
		[data release];
		
	}
	else NSLog(@"FIchier n'existe pas..");
	
	
	//LOCATION MANAGER
	locationManager = [[CLLocationManager alloc] init];
	locationManager.delegate = self;
	locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
	locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
	[locationManager startUpdatingLocation];
	
	
	if (listeFavoris != nil){
		if ([listeFavoris count] > 0) 
			tabBarItem.badgeValue = [NSString stringWithFormat:@"%i", [self.listeFavoris count]];
	}
	else NSLog(@"Liste Favoris est nulle...");
	
	//enable customization of tabBarItems;
	//tabBarController.customizableViewControllers = tabBarController.viewControllers;
	
	//Add the view controller's view to the window and display.
    [self.window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];

    return YES;
}


//creer le chemin vers le fichier de donnees
-(NSString *)dataFilePath{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:kFileName];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
	NSLog(@"App Will Resign Active");
	//creer la liste de nom des controllers du tabBar pour but de sauvegarde
	NSMutableArray *savedOrder = [NSMutableArray arrayWithCapacity:[tabBarController.viewControllers count]];
	NSLog(@"App Will Resign Active");
	NSArray *tabOrderToSave = tabBarController.viewControllers;
		
	for (UIViewController *aViewController in tabOrderToSave) {
		NSLog(@"Title: %@", aViewController.title);
		[savedOrder addObject:aViewController.title];
		NSLog(@"BB");
	}
	
	
	NSMutableData *data = [[NSMutableData alloc]init];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	
	//sauvegarder les favoris dans un plist
	[archiver encodeObject:listeFavoris forKey:kDataKey];
	
	//sauvegarder la configuration du tab bar menu
	[archiver encodeObject:savedOrder forKey:kDataKey2];
	
	[archiver finishEncoding];
	
	BOOL ret = [data writeToFile:[self dataFilePath] atomically:YES];
	
	[archiver release];
	[data release];
	exit(0); //fermer le app
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
	NSLog(@"App did enter background");
	
	
	
		
	
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
	NSLog(@"Will enter foreground");
	
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
	// Do your time consuming setup
	[self parseXML]; //time consuming
	
	[tabBarController viewWillAppear:YES];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
	
	
	
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	NSLog(@"dealloc");
	[list release];
	[lastIndexPathFiltre release];
	[montantMin release];
	[montantMax release];
    [tabBarController release];
	[navController release];
	[listeFavoris release];
	[tabBarItem release];
    [window release];
	[locationManager release];
    [super dealloc];
}


@end
