//
//  ConfigLoader.m
//  SFS2X
//
//  Original development by Infosfer Game Technologies Ltd. | http://www.infosfer.com.
//
//  Maintained and developed by A51 Integrated.
//  Copyright 2012 A51 Integrated | http://a51integrated.com. All rights reserved.
//

#import "SFSEvent.h"
#import "ConfigLoader.h"
#import "ConfigData.h"

@implementation ConfigLoader


-(void)loadConfig:(NSString *)filePath delegate:(id<IConfigLoader>)delegate
{
    
#if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR
    NSData *fileData = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:filePath]];
#else
    NSString * fileName = [filePath stringByDeletingPathExtension];
    NSData *fileData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:@"xml"]];
#endif
    
	
	if (fileData)
    {
        ConfigData *configData = [[ConfigData alloc] init];
        
        // Parse the XML into a dictionary
        NSError *parseError = nil;
        NSDictionary *data = [XMLParser parseXMLData:fileData error:&parseError];
        NSDictionary *root = [data objectForKey:@"SmartFoxConfig"];
        NSString *s = @"text";
        
        configData.host = [[root objectForKey: @"ip"] objectForKey:s];
        configData.port = [[[root objectForKey: @"port"] objectForKey:s] intValue] ;
        configData.udpHost = [[root objectForKey: @"udpHost"] objectForKey:s];
        configData.udpPort = [[[root objectForKey: @"udpPort"] objectForKey:s] intValue];
        configData.zone = [[root objectForKey: @"zone"] objectForKey:s];
        configData.debug = [[[root objectForKey: @"debug"] objectForKey:s] caseInsensitiveCompare:@"true"] == NSOrderedSame ? YES : NO;
        configData.useBlueBox = [[[root objectForKey: @"useBlueBox"] objectForKey:s] caseInsensitiveCompare:@"true"] == NSOrderedSame ? YES : NO;
        configData.httpPort = [[[root objectForKey: @"httpPort"] objectForKey:s] intValue];
        configData.blueBoxPollingRate = [[[root objectForKey: @"blueBoxPollingRate"] objectForKey:s] doubleValue] / 1000;
        
       
        
        SFSEvent *evt = [[SFSEvent alloc] initWithType:SFSEvent_CONFIG_LOAD_SUCCESS params:[NSDictionary dictionaryWithObjectsAndKeys:configData, @"cfg", nil]];
        
        if ([delegate respondsToSelector:@selector(onConfigLoadSuccess:)])
        {
            [delegate onConfigLoadSuccess:evt];
        }
	}
	else
    {
		SFSEvent *evt = [[SFSEvent alloc] initWithType:SFSEvent_CONFIG_LOAD_FAILURE params:nil];
		
		if ([delegate respondsToSelector:@selector(onConfigLoadSuccess:)])
        {
			[delegate onConfigLoadFailure:evt];
		}
	}
}


@end
