//
//  SetRoomVariablesRequest.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 "SetRoomVariablesRequest.h"
#import "SmartFox2XClient.h"
#import "RoomVariable.h"
#import "SFSArray.h"

NSString * const SetRoomVariablesRequest_KEY_VAR_ROOM = @"r";
NSString * const SetRoomVariablesRequest_KEY_VAR_LIST = @"vl";

@implementation SetRoomVariablesRequest

@synthesize roomVariables = _roomVariables;
@synthesize room = _room;


-(id)initWithRoomVariables:(NSArray *)roomVariables room:(id <Room>)room {

	if ((self = [super initWithId:BaseRequest_SetRoomVariables])) {
		self.roomVariables = roomVariables;
		self.room = room;
	}
	
	return self;
}


+(id)requestWithRoomVariables:(NSArray *)roomVariables room:(id <Room>)room {
	SetRoomVariablesRequest *req = [[SetRoomVariablesRequest alloc] initWithRoomVariables:roomVariables room:room];
	return req;
}

+(id)requestWithRoomVariables:(NSArray *)roomVariables {
	SetRoomVariablesRequest *req = [[SetRoomVariablesRequest alloc] initWithRoomVariables:roomVariables room:nil];
	return req;
}

-(void)validate:(SmartFox2XClient *)sfs {
	
	NSMutableArray *errors = [NSMutableArray array];
	
	if (_room == nil && sfs.lastJoinedRoom == nil)
	{
		[errors addObject:@"A Room was not specified and you don't seem joined in any other Room"];
	}
	
	if (_roomVariables == nil || [_roomVariables count] == 0) {
		[errors addObject:@"No variables were specified"];
	}

	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"SetRoomVariables request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	id <ISFSArray> varList = [SFSArray newInstance] ;
	
	for (id rv in _roomVariables) {
		
		if ([rv conformsToProtocol:@protocol(RoomVariable)]) {
			[varList addSFSArray:[(id <RoomVariable>)rv toSFSArray]];
		}
	}
	
	if (_room == nil) {
		_room = sfs.lastJoinedRoom;
	}
	
	[_sfso putSFSArray:SetRoomVariablesRequest_KEY_VAR_LIST value:varList];
	[_sfso putInt:SetRoomVariablesRequest_KEY_VAR_ROOM value:[_room id]];

}


@end
