//
//  NSObject+xmlParser.m
//  melody app
//
//  Created by Odin on 08/09/2016.
//  Copyright © 2016 demain un autre jour. All rights reserved.
//

// !!! DO NOT TYPE CODE AFTER THE END OF FILE TAG !

/*

 +-------------------------------------------------------------------------+
 | This is the XML parser Class , parsing is in three steps                |
 +-------------------------------------------------------------------------+
 |           -first : checking the file parsed URL                         |
 +-------------------------------------------------------------------------+
 |             - 3steps of parsing algorythm                               |
 +-------------------------------------------------------------------------+

 */
 
#import "xmlParser.h"

@implementation XMLToObjectParser

- (NSArray *)items
{
    return items;
}

- (id)parseXMLAtURL:(NSString *)filePath
           toObject:(NSString *)aClassName
         parseError:(NSError **)error
{
    NSInputStream *iStream = [[NSInputStream alloc] initWithFileAtPath:filePath];
    
    [iStream setDelegate:self];
    [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
     forMode:NSDefaultRunLoopMode];
    
    [iStream open];
    [items release];
    items = [[NSMutableArray alloc] init];
    className = aClassName;
    NSXMLParser *parser = [[NSXMLParser alloc] initWithStream:iStream];
    [parser setDelegate:self];
    [parser parse];
    if([parser parserError] && error) {
        *error = [parser parserError];
    }
    [parser release];
    return self;
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    NSLog(@"Open tag: %@", elementName);
    if([elementName isEqualToString:className]) {
        // create an instance of a class on run-time
        item = [[NSClassFromString(className) alloc] init];
    }
    else {
        currentNodeName = [elementName copy];
        currentNodeContent = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
    NSLog(@"Close tag: %@", elementName);
    if([elementName isEqualToString:className]) {
        [items addObject:item];
        [item release];
        item = nil;
    }
    else if([elementName isEqualToString:currentNodeName]) {
        // use key-value coding
        [item setValue:currentNodeContent forKey:elementName];
        
        [currentNodeContent release];
        currentNodeContent = nil;
        
        [currentNodeName release];
        currentNodeName = nil;
    }
}

- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
    [currentNodeContent appendString:string];
}

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

@end
