//
//  XMLParser.m
//  mahammad
//
//  Created on 12/29/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "XMLParser.h"

NSString* kElements = @"Elements";
NSString* kValues = @"Values";

@implementation XMLParser
-(NSArray*) parseXML:(NSString*)str forKey:(NSString*)_mainElement
{
	parserType = kSingleLevel;
	isStart = NO;
	index = -1;
	mainElement = [_mainElement copy];

	elements = [[NSMutableArray alloc] initWithCapacity:32];
	
	NSRange prefix = [str rangeOfString:@"<"]; 
	if(prefix.location != NSNotFound && prefix.location > 0)
	{
		str = [str substringFromIndex:prefix.location];
	}
	NSData* data = [str dataUsingEncoding:NSASCIIStringEncoding];
	NSXMLParser* xml = [[NSXMLParser alloc] initWithData:data];
	
	[xml setDelegate:self];
	[xml parse];
	[xml release];
	
	return elements;
}

-(NSMutableDictionary*) parseXML:(NSString*)str mainElement:(NSString*)_mainElement
{
	parserType = kTwoLevel;
	isStart = NO;
	index = -1;
	mainElement = [_mainElement copy];
	
	elements = [[NSMutableArray alloc] initWithCapacity:32];
	values = [[NSMutableArray alloc] initWithCapacity:32];
	
	NSData* data = [str dataUsingEncoding:NSASCIIStringEncoding];
	NSXMLParser* xml = [[NSXMLParser alloc] initWithData:data];
	
	[xml setDelegate:self];
	[xml parse];
	[xml release];
	
	resultData = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
				  values,kValues,
				  elements,kElements,
				  nil
				  ];
	
	return resultData;
}

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if(parserType == kSingleLevel)
	{
		if([elementName isEqualToString:mainElement])
		{
			isStart = YES;
			index++;
		}
	}
	else if(parserType == kTwoLevel)
	{
		if([elementName isEqualToString:mainElement])
		{
			isStart = YES;
			index++;
			currentItems = [[NSMutableDictionary alloc] initWithCapacity:32];
		}
		else if(isStart)
		{
			if(index == 0)
				[elements addObject:elementName];
			
			if(currentElement)
				[currentElement release];
			
			currentElement = [elementName retain];
		}
		
	}
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if(parserType == kSingleLevel)
	{
		if(isStart)
		{
			[elements addObject:string];
		}
	}
	else if(parserType == kTwoLevel)
	{
		if(isStart)
		{
			
			[currentItems setObject:string forKey:currentElement];
		}
	}
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	if(parserType == kSingleLevel)
	{
		isStart = NO;
	}
	else if(parserType == kTwoLevel)
	{
		if([elementName isEqualToString:mainElement])
		{
			isStart = NO;
			[values addObject:currentItems];
		}
		
	}
}

-(void) dealloc
{
    NSLog(@"dealloc12");

	[mainElement release];
    [currentItems release]; //newly added
    
    
	[super dealloc];
}


@end
