//
//  AddBuddyRequest.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 "AddBuddyRequest.h"
#import "SmartFox2XClient.h"
#import "Buddy.h"

NSString * const AddBuddyRequest_KEY_BUDDY_NAME = @"bn";

@implementation AddBuddyRequest

@synthesize name = _name;



-(id)initWithBuddyName:(NSString *)buddyName {
	
	if ((self = [super initWithId:BaseRequest_AddBuddy])) {
		self.name = buddyName;
	}
	
	return self;
}

+(id)requestWithBuddyName:(NSString *)buddyName {
	AddBuddyRequest *req = [[AddBuddyRequest alloc] initWithBuddyName:buddyName];
	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 (_name == nil || [_name length] < 1) {
		[errors addObject:[NSString stringWithFormat: @"Invalid buddy name: %@", _name]];
	}
	
	if ([sfs.buddyManager myOnlineState] == NO) {
		[errors addObject:@"Can't add buddy while offline"];
	}
	
	id <Buddy> buddy = [sfs.buddyManager getBuddyByName:_name];
	
	if (buddy != nil && ![buddy isTemp]) {
		[errors addObject:[NSString stringWithFormat:@"Can't add buddy, it is already in your list: %@", _name]];
	}
	
	
	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"BuddyList request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	[_sfso putUtfString:AddBuddyRequest_KEY_BUDDY_NAME value:_name];
	
}



@end
