//
//  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.
	return [listeFavoris count];
}

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

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	
    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;
		cell.showsReorderControl = YES;
    }
    
    // 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];
	
	CLLocation *location=[[CLLocation alloc]initWithLatitude:unImmeuble.latitude longitude:unImmeuble.longitude];
	cell.distance.text = [NSString stringWithFormat:@"%.0f km", [appDelegate.locationManager.location distanceFromLocation:location]/1000];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
	//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


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
	return YES;
}


-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath{
	
	NSUInteger fromRow = [fromIndexPath row];
	NSUInteger toRow = [toIndexPath row];
	
	id object = [[listeFavoris objectAtIndex:fromRow]retain];
	[listeFavoris removeObjectAtIndex:fromRow];
	[listeFavoris insertObject:object atIndex:toRow];
	[object release];
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	//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
	[self.listeFavoris removeObjectAtIndex:indexPath.row];
	appDelegate.listeFavoris = self.listeFavoris;
	[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;
	
	//MISE A JOUR CLICKER DES FAVORIS
	appDelegate.tabBarItem.badgeValue = ([appDelegate.listeFavoris count] > 0) ? [NSString stringWithFormat:@"%i", [appDelegate.listeFavoris count]] : nil ;

       
}


- (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];
	detailController.hidesBottomBarWhenPushed = YES;
    [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

