//
//  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;


-(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];
	if (appDelegate.reload)
	{
		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];
		appDelegate.reload = NO;
	}
	NSLog(@"View will appear");

}

//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];
	NSLog(@"View did load");
	[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];
}


// 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];
	cell.typeImmeuble.text = unImmeuble.style;
	cell.adresse.text = unImmeuble.adresse;
	cell.prix.text = [NSString stringWithFormat:@"%i", unImmeuble.prix];
	cell.distance.text = [NSString stringWithFormat:@"%i km", unImmeuble.distance];
	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
