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

#import "FavoritesViewController.h"
#import "AgenceAppDelegate.h"
#import "Immeuble.h"
#import "CustomCell.h"
#import "AsyncImageView.h"
#import "DetailViewController.h"


@implementation FavoritesViewController;
@synthesize listeFavoris;
@synthesize table;


#pragma mark -
#pragma mark View lifecycle

-(IBAction)toggleEdit:(id)sender {
	[self.tableView setEditing:!self.tableView.editing animated:YES];
	if (self.tableView.editing)
		[self.navigationItem.rightBarButtonItem setTitle:@"Terminé"];
	else 
		[self.navigationItem.rightBarButtonItem setTitle:@"Éditer"];

}

- (void)viewDidLoad {

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Editer" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit:)];
	self.navigationItem.rightBarButtonItem = button;
	[button release];
	[super viewDidLoad];
}



- (void)viewWillAppear:(BOOL)animated {
    AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
    self.title = @"Favoris";
	self.listeFavoris = appDelegate.listeFavoris;
	[self.tableView reloadData];
	NSLog(@"Nombre de favoris: %i",[appDelegate.listeFavoris count]);
	
	//MISE A JOUR DE LETAT DU BOUTON D'EDITION
	if ([self.tableView numberOfRowsInSection:0] == 0)
	{
		[self.tableView setEditing:NO animated:NO];
		self.navigationItem.rightBarButtonItem.enabled = NO;
	}
	else 
	{
		self.navigationItem.rightBarButtonItem.enabled = YES;
		[self.navigationItem.rightBarButtonItem setTitle:@"Éditer"];
	}
	[super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

- (void)viewWillDisappear:(BOOL)animated {
	[self.tableView setEditing:NO animated:YES];
	
    [super viewWillDisappear:animated];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// 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.
    AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	return [appDelegate.listeFavoris 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.listeFavoris 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;
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSUInteger row = [indexPath row];
	
	//METTRE A JOUR LA LISTE DES FAVORIS DANS APP DELEGATE
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
	Immeuble *unImmeuble = [[[Immeuble alloc] init] autorelease];
	unImmeuble = [appDelegate.listeFavoris objectAtIndex:row];
	[array removeObjectIdenticalTo:unImmeuble];
	appDelegate.listeFavoris = array;
	[array release];
	
	//MISE A JOUR CLICKER DES FAVORIS
	appDelegate.tabBarItem.badgeValue = ([appDelegate.listeFavoris count] > 0) ? [NSString stringWithFormat:@"%i", [appDelegate.listeFavoris count]] : nil ;
	
	//DESELECTIONNER ET METTRE A JOUR
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

	//MISE A JOUR DE LETAT DU BOUTON D'EDITION
	if ([appDelegate.listeFavoris count] == 0)
	{
		[self.tableView setEditing:NO animated:NO];
		self.navigationItem.rightBarButtonItem.enabled = NO;
	}
	else 
		self.navigationItem.rightBarButtonItem.enabled = YES;
       
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

#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.listeFavoris objectAtIndex:row];
    [self.navigationController pushViewController:detailController animated:YES];
}

#pragma mark -
#pragma mark Memory management

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

- (void)viewDidUnload {
    self.listeFavoris = nil;
	self.table = nil;
}


- (void)dealloc {
	[listeFavoris release];
	[table release];
    [super dealloc];
}


@end

