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

NSString * const SetBuddyVariablesRequest_KEY_BUDDY_NAME = @"bn";
NSString * const SetBuddyVariablesRequest_KEY_BUDDY_VARS = @"bv";

@implementation SetBuddyVariablesRequest

@synthesize buddyVariables = _buddyVariables;


-(id)initWithBuddyVariables:(NSArray *)buddyVariables {
	if ((self = [super initWithId:BaseRequest_SetBuddyVariables])) {
		self.buddyVariables = buddyVariables;
	}
	
	return self;
}

+(id)requestWithBuddyVariables:(NSArray *)buddyVariables {
	SetBuddyVariablesRequest *req = [[SetBuddyVariablesRequest alloc] initWithBuddyVariables:buddyVariables];
	return req;
}

-(void)validate:(SmartFox2XClient *)sfs {
	
	NSMutableArray *errors = [NSMutableArray array];
	
	if (![sfs.buddyManager isInited]) {
		[errors addObject:@"BuddyList is not inited. Please send an InitBuddyRequest first."];
	}
	
	if ([sfs.buddyManager myOnlineState] == NO) {
		[errors addObject:@"Can't set buddy variables while offline"];
	}
	
	if (_buddyVariables == nil || [_buddyVariables count] == 0) {
		[errors addObject:@"No variables were specified"];
	}	
	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"SetBuddyVariables request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	id <ISFSArray> varList = [SFSArray newInstance];
	
	for (id bVar in _buddyVariables){
		if ([bVar conformsToProtocol:@protocol(BuddyVariable)]) {
			[varList addSFSArray:[(id <BuddyVariable>)bVar toSFSArray]];
		}
	}
	
	[_sfso putSFSArray:SetBuddyVariablesRequest_KEY_BUDDY_VARS value:varList];
	
}

@end
