//
//  XMLParser.m
//  Axis
//
//  Created by Olivier Savard on 10-03-01.
//  Copyright 2010 OSInfo Informatique. All rights reserved.
//

#import "XMLParser.h"
#import "ListeViewController.h"
#import "Immeuble.h"
#import "AgenceAppDelegate.h"

@implementation XMLParser

- (XMLParser *) initXMLParser {
	
	[super init];
	
	appDelegate = (AgenceAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
	attributes:(NSDictionary *)attributeDict {
	
	if([elementName isEqualToString:@"immeubles"]) 
	{
		//Initialize the array.
		appDelegate.list = [[NSMutableArray alloc] init];
	}
	
	else if([elementName isEqualToString:@"immeuble"]) 
	{
		//Initialiser l'immeuble.
		unImmeuble = [[Immeuble alloc] init];
		
		//Extract the attribute here.
		unImmeuble.immeubleID = [[attributeDict objectForKey:@"id"] integerValue];
		unImmeuble.adresse = [[attributeDict objectForKey:@"adresse"] stringValue];
		
		/*TESTS */
	
		
		NSLog(@"Lecture de l'immeuble NO :%i", unImmeuble.immeubleID);
		NSLog(@"et de style : %@",unImmeuble.style);
		NSLog(@"adresse :%@", unImmeuble.adresse);
		NSLog(@"prix: %i",unImmeuble.prix);
		NSLog(@"distance: %i.",unImmeuble.distance); 
	}
	
	NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	
	if(!currentElementValue)
		currentElementValue = [[NSMutableString alloc] initWithCapacity:50];
	
	[currentElementValue appendString:string];
	
	NSLog(@"Processing Value: %@", currentElementValue);
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	if([elementName isEqualToString:@"immeubles"])
		return;
	
	//There is nothing to do if we encounter the Books element here.
	//If we encounter the Book element however, we want to add the book object to the array
	// and release the object.
	if([elementName isEqualToString:@"immeuble"]) {
		
		[appDelegate.list addObject:unImmeuble];
		[unImmeuble  release];
	
	}
	else
	{
		[unImmeuble setValue:currentElementValue forKey:elementName];
		
		if (elementName == @"style")
		{
			NSLog(@"Style: %@", unImmeuble.style);
		}
		else if (elementName == @"type")
		{
			NSLog(@"Type: %i", unImmeuble.type);
		}
		else if (elementName == @"adresse")
		{
			NSLog(@"adresse: %@", unImmeuble.adresse);
		}
		else if (elementName == @"prix")
		{
			NSLog(@"prix: %@", unImmeuble.prix);
		}
		else if (elementName == @"distance")
		{
			NSLog(@"distance: %@", unImmeuble.distance);
		}			
	}
	
	[currentElementValue release];
	currentElementValue = nil;
}

- (void) dealloc {
	
	[unImmeuble release];
	[currentElementValue release];
	[super dealloc];
}

@end
