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

#import "DetailViewController.h"
#import "AgenceAppDelegate.h"
#import "AsyncImageView.h"
#import "MapViewController.h"


@implementation DetailViewController
@synthesize unImmeuble;
@synthesize styleLabel;
@synthesize adresseLabel;
@synthesize prixLabel;
@synthesize mainImageView;
@synthesize latitude;
@synthesize longitude;
@synthesize map;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/
-(void)getItineraire{
	NSString* url = [NSString stringWithFormat: @"http://maps.google.fr/maps?saddr=%f,%f&daddr=%f,%f", 
					 map.userLocation.coordinate.latitude, map.userLocation.coordinate.longitude, unImmeuble.latitude, unImmeuble.longitude];
    //ouvrir dans maps avec itineraire de saddr a daddr
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

-(void)ajouterFavoris{
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
	
	if (![array containsObject:unImmeuble]) //SI L'IMMEUBLE N'EST PAS DANS LES FAVORIS
	{
		//AJOUT DANS FAVORIS
		[array addObject:unImmeuble];
		//self.navigationItem.rightBarButtonItem.title = @"Retirer";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_remove.png"];
	}
	else 
	{
		//RETRAIT DE FAVORIS
		[array removeObject:unImmeuble];
		//self.navigationItem.rightBarButtonItem.title = @"Ajouter";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_add.png"];
	}
	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 ;
	//MISE A JOUR DE LA MAP (PIN)
	[map removeAnnotation:unImmeuble];
	[map addAnnotation:unImmeuble];
}


-(void)viewWillAppear:(BOOL)animated {
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
	
	self.navigationItem.rightBarButtonItem.enabled = YES;
	
	if (![array containsObject:unImmeuble]) //SI L'IMMEUBLE N'EST PAS DANS LES FAVORIS
	{
		//self.navigationItem.rightBarButtonItem.title = @"Ajouter";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_add.png"];
	}
	else 
	{
		//self.navigationItem.rightBarButtonItem.title = @"Retirer";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_remove.png"];
	}
	[array release];
	
	//INFOS GENERALES
	styleLabel.text = unImmeuble.style;
	adresseLabel.text = unImmeuble.adresse;
	prixLabel.text = [NSString stringWithFormat:@"%i $",unImmeuble.prix];
	
	
	NSLog(@"latitude: %f",unImmeuble.latitude);
	NSLog(@"longitude: %f",unImmeuble.longitude);
	latitude = [NSString stringWithFormat:@"%f",unImmeuble.latitude];
	longitude = [NSString stringWithFormat:@"%f",unImmeuble.longitude];
	
	/*
	//LOAD DE L'IMAGE DE FACON ASYNCHRONE
	CGRect frame;
	frame.size.width=280; frame.size.height=180;
	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];
	[self.mainImageView addSubview:asyncImage];
	[stringUrl release];
	*/
	
	//creer la clee pour dictionaire d'image (cache)
	NSString *key = [NSString stringWithFormat:@"%i", unImmeuble.immeubleID];
	if ([appDelegate.imagesCacheLarge objectForKey:key] != nil)  //SI IL Y A UNE IMAGE DANS LA CACHE
	{
		NSLog(@"!=nil..");
		[self.mainImageView addSubview:[appDelegate.imagesCacheLarge objectForKey:key]];
	}
	else
	{
		//LOAD DE L'IMAGE DE FACON ASYNCHRONE
		CGRect frame;
		frame.size.width=280; frame.size.height=180;
		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];
		[self.mainImageView addSubview:asyncImage];
		[stringUrl release];
		
		//monter la liste d'image (cache), on ajoute l'image si elle n'est pas deja presente..
		[appDelegate.imagesCacheLarge setObject:asyncImage forKey:key];
	}
	
	
	//MAP
	map.showsUserLocation = NO;
	map.showsUserLocation = YES;
	map.mapType = MKMapTypeStandard;
	map.delegate = self;
	
	/*Region and Zoom*/
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.005;
	span.longitudeDelta=0.005;
	
	//attribuer le centre choisi
	CLLocationCoordinate2D location ;
	location.latitude = unImmeuble.latitude;
	location.longitude = unImmeuble.longitude;
	
	region.span=span;
	region.center=location;
	
	[map setRegion:region animated:TRUE];
	[map regionThatFits:region];
	
	//LOADER LE MARKER
	unImmeuble.coordinate = location;
	[map addAnnotation:unImmeuble];
	
	[super viewWillAppear:YES];
}



- (void)viewDidLoad {
	//SCROLL VIEW
	scroll.contentSize = CGSizeMake(320, 560);   //important
	//CREATION DU BOUTON DE NAVIGATION DE DROITE (FAVORIS)
	UIBarButtonItem *button = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"favorite_add.png"] 
								style:UIBarButtonItemStyleBordered target:self action:@selector(ajouterFavoris)]autorelease];
	self.navigationItem.rightBarButtonItem = button;
		
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
	
	if (![array containsObject:unImmeuble])
	{
		//self.navigationItem.rightBarButtonItem.title = @"Ajouter";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_add.png"];
	}
	else 
	{
		//self.navigationItem.rightBarButtonItem.title = @"Retirer";
		self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"favorite_remove.png"];
	}
	//MISE A JOUR CLICKER DES FAVORIS
	appDelegate.tabBarItem.badgeValue = ([appDelegate.listeFavoris count] > 0) ? [NSString stringWithFormat:@"%i", [appDelegate.listeFavoris count]] : nil ;
	
	
	[array release];
	[super viewDidLoad];
}


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

- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
	AgenceAppDelegate * appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	static NSString *placemarkIdentifier = @"Map Location Identifier";
	if ([annotation isKindOfClass:[Immeuble class]]) {
		MKPinAnnotationView *pin = (MKPinAnnotationView *) [theMapView dequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];
		if (pin == nil) {
			pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:placemarkIdentifier];
			
		}
		else {
			pin.annotation = annotation;
		}
		
		pin.enabled = YES;
		pin.animatesDrop = YES;
		NSMutableArray *array = [[NSMutableArray alloc] initWithArray:appDelegate.listeFavoris];
		if ([array indexOfObject:(Immeuble *)annotation] == NSNotFound )
		{
			NSLog(@"Pin immeuble pas dans favoris");
			pin.pinColor = MKPinAnnotationColorGreen;
		}
		else 
		{
			NSLog(@"Pin immeuble dans favoris");
			pin.pinColor = MKPinAnnotationColorRed;
		}
		[array release];
		
		
		
		//[self performSelector:@selector(openCallout:) withObject:annotation afterDelay:0.5];
		NSLog(@"Dans mapView...");
		return pin;
	}
	return nil;
}


-(void)viewDidDisappear:(BOOL)animated{
	[self.navigationController popToRootViewControllerAnimated: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 {
    self.unImmeuble = nil;
	self.prixLabel = nil;
	self.styleLabel = nil;
	self.adresseLabel = nil;
	self.mainImageView = nil;
	self.latitude = nil;
	self.longitude = nil;
	[super viewDidUnload];
}


- (void)dealloc {
	[unImmeuble release];
	[prixLabel release];
	[styleLabel release];
	[adresseLabel release];
	[mainImageView release];
	[latitude release];
	[longitude release];
    [super dealloc];
}


@end
