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

NSString * const BlockBuddyRequest_KEY_BUDDY_NAME = @"bn";
NSString * const BlockBuddyRequest_KEY_BUDDY_BLOCK_STATE = @"bs";
NSString * const BlockBuddyRequest_KEY_BUDDY = @"bd";

@implementation BlockBuddyRequest

@synthesize buddyName = _buddyName;



-(id)initWithBuddyName:(NSString *)buddyName blocked:(BOOL)blocked{
	
	if ((self = [super initWithId:BaseRequest_BlockBuddy])) {
		self.buddyName = buddyName;
		_blocked = blocked;
	}
	
	return self;
}

+(id)requestWithBuddyName:(NSString *)buddyName blocked:(BOOL)blocked {
	BlockBuddyRequest *req = [[BlockBuddyRequest alloc] initWithBuddyName:buddyName blocked:blocked];
	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 (_buddyName == nil || [_buddyName length] < 1) {
		[errors addObject:@"Invalid buddy name."];
	}
	
	if ([sfs.buddyManager myOnlineState] == NO) {
		[errors addObject:@"Can't block buddy while offline"];
	}
	
	id <Buddy> buddy = [sfs.buddyManager getBuddyByName:_buddyName];
	
	if (buddy == nil) {
		[errors addObject:[NSString stringWithFormat:@"Can't block buddy, it's not in your list: %@", _buddyName]];
	}
	else if ([buddy isBlocked] == _blocked){
		[errors addObject:[NSString stringWithFormat:@"BuddyBlock flag is already in the requested state: %@, for buddy: %@", _blocked ? @"'YES'" : @"'NO'", buddy]];
	}
	
	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"BuddyList request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	[_sfso putUtfString:BlockBuddyRequest_KEY_BUDDY_NAME value:_buddyName];
	[_sfso putBool:BlockBuddyRequest_KEY_BUDDY_BLOCK_STATE value:_blocked];
	
}



@end
