//
//  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";
	[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];
	
	[self.tableView reloadData];

}

//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];
	[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];
}


- (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(90.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(100.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(100.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;
    
	//LOAD DE L'IMAGE DE FACON ASYNCHRONE
	CGRect frame;
	frame.size.width=60; frame.size.height=40;
	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];
	
	return cell;
}

#pragma mark -
#pragma mark Table View Delegate Methods

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
	detailController.unImmeuble = [self.list objectAtIndex:row];
    [self.navigationController pushViewController:detailController animated:YES];
	[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
