//
//  ExtensionRequest.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 "ExtensionRequest.h"
#import "SFSObject.h"


NSString * const ExtensionRequest_KEY_CMD = @"c";
NSString * const ExtensionRequest_KEY_PARAMS = @"p";
NSString * const ExtensionRequest_KEY_ROOM = @"r";

@implementation ExtensionRequest

-(id)initWithExtCmd:(NSString *)extCmd params:(id<ISFSObject>)params room:(id<Room>)room isUDP:(BOOL) udp
{
	if ((self = [super initWithId:BaseRequest_CallExtension]))
    {
		_extCmd = extCmd;
        _params = (params == nil ? [[SFSObject alloc]init] : params);
		_room = room;
        
        self.isUDP = udp;
		
		_targetController = 1;
	}
	
	return self;
}

+(id)requestWithExtCmd:(NSString *)extCmd params:(id<ISFSObject>)params room:(id<Room>)room
{
	ExtensionRequest *req = [[ExtensionRequest alloc] initWithExtCmd:extCmd params:params room:room isUDP:NO];
	return req;
}

+(id)requestWithExtCmd:(NSString *)extCmd params:(id<ISFSObject>)params
{
	ExtensionRequest *req = [[ExtensionRequest alloc] initWithExtCmd:extCmd params:params room:nil isUDP:NO];
	return req;
}

+(id)requestWithExtCmd:(NSString *)extCmd params:(id<ISFSObject>)params room:(id<Room>)room udp:(BOOL) udp
{
	ExtensionRequest *req = [[ExtensionRequest alloc] initWithExtCmd:extCmd params:params room:room isUDP:udp];
	return req;
}

+(id)requestWithExtCmd:(NSString *)extCmd params:(id<ISFSObject>)params udp:(BOOL) udp
{
	ExtensionRequest *req = [[ExtensionRequest alloc] initWithExtCmd:extCmd params:params room:nil isUDP:udp];
	return req;
}

-(void)validate:(SmartFox2XClient *)sfs
{
	NSMutableArray *errors = [NSMutableArray array];
	
	if(_extCmd == nil || [_extCmd length] == 0) {
		[errors addObject:@"Missing extension command"];
	}
	
	if(_params == nil) {
		[errors addObject:@"Missing extension parameters"];
	}
	
	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"ExtensionCall request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs
{
	[_sfso putUtfString:ExtensionRequest_KEY_CMD value:_extCmd];
	[_sfso putInt:ExtensionRequest_KEY_ROOM value:(_room == nil) ? -1 : [_room id]];
	[_sfso putSFSObject:ExtensionRequest_KEY_PARAMS value:_params];
}


@end
