//
//  ExtensionController.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 "ExtensionController.h"
#import "SmartFox2XClient.h"
#import "BitSwarmClient.h"
#import "Logger.h"
#import "SFSEvent.h"
#import "IMessage.h"

NSString * const ExtensionController_KEY_CMD = @"c";
NSString * const ExtensionController_KEY_PARAMS = @"p";
NSString * const ExtensionController_KEY_ROOM = @"r";


@implementation ExtensionController

@synthesize sfs = _sfs;
@synthesize bitSwarm = _bitSwarm;


-(id)initWithBitSwarmClient:(BitSwarmClient *)bitSwarm {
	if ((self = [super init])) {
		self.bitSwarm = bitSwarm;
		self.sfs = bitSwarm.sfs;
	}
	return self;
}

-(void)handleMessage:(id <IMessage>)message
{
	if (_sfs.debug)
		[_log info:[message description]];
	
	
	id <ISFSObject> obj = [message content];
	NSMutableDictionary *evtParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:[obj getUtfString:ExtensionController_KEY_CMD], @"cmd", [obj getSFSObject:ExtensionController_KEY_PARAMS], @"params", nil];
    
    if ([obj containsKey:ExtensionController_KEY_ROOM])
    {
        NSNumber *roomId = [NSNumber numberWithInt:(int)[obj getInt:ExtensionController_KEY_ROOM]];
        [evtParams setObject:roomId forKey:@"sourceRoom"];
        
        // Add only if exits, if null this would raise an exception when adding to the dictionary
        id<Room> theRoom = [self.sfs getRoomById: [roomId integerValue]];
        
        if (theRoom != nil)
            [evtParams setObject: theRoom forKey:@"room"];
    }
    
	
	if ([_sfs.delegate respondsToSelector:@selector(onExtensionResponse:)]) {
		[_sfs.delegate onExtensionResponse:[[SFSEvent alloc] initWithType:SFSEvent_EXTENSION_RESPONSE params:evtParams]];
	}
}



@end
