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

#import "ListeViewController.h"
#import "CustomCell.h"
#import "Immeuble.h"
#import "AgenceAppDelegate.h"
#import "FiltreViewController.h"
#import "AsyncImageView.h"
#import "DetailViewController.h"

@implementation ListeViewController
@synthesize list;
@synthesize filtreController;
@synthesize tri;
@synthesize locationManager;




-(IBAction)filtrer{
	FiltreViewController *unFiltreController = [[FiltreViewController alloc]initWithNibName:@"FiltreViewController" bundle:nil];
	self.filtreController = unFiltreController;
	[unFiltreController release];
	filtreController.title = @"Filtre";
	filtreController.hidesBottomBarWhenPushed = YES;
	[self.navigationController pushViewController:filtreController animated:YES];
	
}

-(void)viewWillAppear:(BOOL)animated{
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];

	NSLog(@"View will appear");
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.list];
	for (int i=0; i < [array count]; i++) 
		{
		Immeuble *unImmeuble = [array objectAtIndex:i];
		NSString *min = [NSString stringWithFormat:@"%@", appDelegate.montantMin];
		NSString *max = [NSString stringWithFormat:@"%@", appDelegate.montantMax];	
			NSLog(@"type filtrer: %i",appDelegate.lastIndexPathFiltre.row);
		if (( ( [min integerValue] != 0) && unImmeuble.prix < [min integerValue]) ||  //un montant minimum est établi && le montant de l'immeuble depasse ce dernier
			( ( [max integerValue] != 0) && unImmeuble.prix > [max integerValue]) ||  //un montant maximum est établi && le montant de l'immeuble plus petit
			//un type de propriété recherché est précisé et ne correspond pas a celui de l'immeuble en cour 
			( appDelegate.lastIndexPathFiltre.row != kTypeTous && unImmeuble.type != appDelegate.lastIndexPathFiltre.row ) ) 			
		{
			[array removeObjectAtIndex:i];
			i--;
		}
	}
	self.list = array;
	[array release];
	
	//METTRE LORDRE DE LA LISTE AFFICHEE A JOUR EN APPELANT TOGGLEORDER
	NSLog(@"Index du segment control %i",[self.tri selectedSegmentIndex]);
	self.tri.selectedSegmentIndex = 0;
	
	[self toggleOrder:self.tri];
	
	NSLog(@"Avant table view reload");
	[self.tableView reloadData];
	NSLog(@"Avant table view reload");
	

}

//TRI DE LA LISTE PRINCIPALE DES PROPRIETES SELON LA DISTANCE OU LE PRIX
-(IBAction)toggleOrder:(id)sender{
	
	if ([sender selectedSegmentIndex] == 0) 
	{
		NSSortDescriptor *firstDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"distance"
																		 ascending:YES] autorelease];
		
		NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
		
		// new and shiny sorted array
		NSArray *sortedObjects = [self.list sortedArrayUsingDescriptors:sortDescriptors];
		self.list = sortedObjects;
	}
	else 
	{
		NSSortDescriptor *firstDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"prix"
																		 ascending:YES] autorelease];
		
		NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor,nil];
		
		// new and shiny sorted array
		NSArray *sortedObjects = [self.list sortedArrayUsingDescriptors:sortDescriptors];
		self.list = sortedObjects;
		
	}
	[self.tableView reloadData];
}


- (void)viewDidLoad {
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	self.list=appDelegate.list;
	
	//TRI PAR DISTANCE (DEFAULT SEGMENT CONTROL)
	NSSortDescriptor *firstDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"distance"
																	 ascending:YES] autorelease];
	NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
	// new and shiny sorted array
	NSArray *sortedObjects = [self.list sortedArrayUsingDescriptors:sortDescriptors];
	
	self.list = sortedObjects;
	
	[self.tableView reloadData];
	
	//si serveur est down
	if (!appDelegate.success){
		Immeuble *unImmeuble  = [[Immeuble alloc]init];
		unImmeuble.style = @"Aucune proprietes...";
		NSMutableArray *listeVide = [[NSMutableArray alloc]initWithObjects:unImmeuble, nil];
		self.list = listeVide;

	}
		
	[super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [list count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 60;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	// CREER LA VUE PARENTE QUI CONTIENDRA LE LABEL DU FILTRE
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 15.0)];
	customView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.9];
	
	// CREER LE LABEL DU FILTRE
	UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
	headerLabel.backgroundColor = [UIColor clearColor];
	headerLabel.opaque = YES;
	headerLabel.textColor = [UIColor blackColor];
	headerLabel.highlightedTextColor = [UIColor whiteColor];
	headerLabel.font = [UIFont boldSystemFontOfSize:12];
	headerLabel.frame = CGRectMake(110.0, 0.0, 320.0, 15.0);
	
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];		
	switch (appDelegate.lastIndexPathFiltre.row) {
		case 1:
		{
			headerLabel.text = @"Filtre: Chalet";
			break;
		}
		case 2:
		{
			headerLabel.text =  @"Filtre: Condo";
			break;
		}
		case 3:
		{
			headerLabel.text =  @"Filtre: Maison";
			break;
		}
		case 4:
		{
			headerLabel.text =  @"Filtre: Bord de lac";
			break;
		}
		case 5:
		{
			headerLabel.text =  @"Filtre: Pente de ski";
			break;
		}
		default:
			headerLabel.text =  @"";
			break;	
	}
	NSLog(@"Montant minimum %@",appDelegate.montantMin);
	NSLog(@"Montant maximum %@",appDelegate.montantMax);
	if (appDelegate.montantMin != nil && appDelegate.montantMax != nil){
		headerLabel.text = [NSString stringWithFormat:@"%@ %@ - %@", headerLabel.text,appDelegate.montantMin,appDelegate.montantMax];
		headerLabel.frame = CGRectMake(100.0, 0.0, 320.0, 15.0);
		NSLog(@"A");
	}
	else if(appDelegate.montantMin == nil && appDelegate.montantMax != nil){
		headerLabel.text = [NSString stringWithFormat:@"%@ max %@", headerLabel.text,appDelegate.montantMax];
		headerLabel.frame = CGRectMake(105.0, 0.0, 320.0, 15.0);
		NSLog(@"B");
	}
	else if(appDelegate.montantMin != nil && appDelegate.montantMax == nil){
		headerLabel.text = [NSString stringWithFormat:@"%@ min %@", headerLabel.text,appDelegate.montantMin];
		headerLabel.frame = CGRectMake(105.0, 0.0, 320.0, 15.0);
		NSLog(@"C");
	}
	NSLog(@"HEADEr LABEL: %@",headerLabel.text);
	[customView addSubview:headerLabel];
	if (appDelegate.lastIndexPathFiltre.row != 0 || ( appDelegate.montantMax != nil || appDelegate.montantMin != nil ) )
		return customView;
	else return nil;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 15.0;
}

/*
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];		
	switch (appDelegate.lastIndexPathFiltre.row) {
		case 1:
		{
			return @"Filtre: Chalet";
			break;
		}
		case 2:
		{
			return @"Filtre: Condo";
			break;
		}
		case 3:
		{
			return @"Filtre: Maison";
			break;
		}
		case 4:
		{
			return @"Filtre: Bord de lac";
			break;
		}
		case 5:
		{
			return @"Filtre: Pente de ski";
			break;
		}
		default:
			return @"";
			break;	
	}
} 
*/

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CustomCellIdentifier = @"CustomCell";
    
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
		for (id oneObject in nib)
			if ([oneObject isKindOfClass:[CustomCell class]])
				cell = (CustomCell *)oneObject;
    }
    
    // Configure the cell...
    NSUInteger row = indexPath.row;
	Immeuble *unImmeuble = [self.list objectAtIndex:row];
	
	// Definir la distance de la localisation presente
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	CLLocation *location=[[CLLocation alloc]initWithLatitude:unImmeuble.latitude longitude:unImmeuble.longitude];
	cell.distance.text = [NSString stringWithFormat:@"%.0f km", [appDelegate.locationManager.location distanceFromLocation:location]/1000];
	
	//RECALCULER LA DISTANCE A CHAQUE FOIS QUE LE TABLEVIEW EST MIS-A-JOUR
	//unImmeuble.distance = ([appDelegate.locationManager.location distanceFromLocation:location]/1000);

	
	//reste des informations
	cell.typeImmeuble.text = unImmeuble.style;
	cell.adresse.text = unImmeuble.adresse;
	cell.prix.text = [NSString stringWithFormat:@"%i", unImmeuble.prix];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
	//favori ? Si oui on ajoute un icone de favori dans la cellule
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
	if ([array containsObject:unImmeuble]) //SI L'IMMEUBLE N'EST PAS DANS LES FAVORIS
	{
		UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Favorites-icon.png"]];
		[cell.favori addSubview:view];
		[view release];
	}
	
	//creer la clee pour dictionaire d'image (cache)
	NSString *key = [NSString stringWithFormat:@"%i", unImmeuble.immeubleID];
	if ([appDelegate.imagesCacheSmall objectForKey:key] != nil)  //SI IL Y A UNE IMAGE DANS LA CACHE
	{
		NSLog(@"!=nil..");
		[cell.photo addSubview:[appDelegate.imagesCacheSmall objectForKey:key]];
	}
	else
	{
		//LOAD DE L'IMAGE DE FACON ASYNCHRONE
		CGRect frame;
		frame.size.width=75; frame.size.height=59;
		frame.origin.x=0; frame.origin.y=0;
		AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame]autorelease];
		asyncImage.tag = 999;
		NSString *stringUrl = [[NSString alloc] initWithFormat:@"http://www.web-k.org/os/imgmaisons/%i.jpg",unImmeuble.immeubleID];
		NSURL *url = [NSURL URLWithString:stringUrl];
		[asyncImage loadImageFromURL:url];
		[cell.photo addSubview:asyncImage];
		[stringUrl release];
		
		//monter la liste d'image (cache), on ajoute l'image si elle n'est pas deja presente..
		[appDelegate.imagesCacheSmall setObject:asyncImage forKey:key];
	}
	
	return cell;
}

#pragma mark -
#pragma mark Table View Delegate Methods

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    DetailViewController *detail = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
	detail.unImmeuble = [self.list objectAtIndex:row];
	detail.hidesBottomBarWhenPushed = YES;
	[self.navigationController pushViewController:detail animated:YES];
	//[detail release];  //cannot release...
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

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


- (void)dealloc {
	[list release];
	[filtreController release];
	[tri release];
    [super dealloc];
}

@end
