//
//  FindUsersRequest.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 "FindUsersRequest.h"
#import "MatchExpression.h"
#import "Logger.h"
#import "Room.h"

NSString * const FindUsersRequest_KEY_EXPRESSION = @"e";
NSString * const FindUsersRequest_KEY_GROUP = @"g";
NSString * const FindUsersRequest_KEY_ROOM = @"r";
NSString * const FindUsersRequest_KEY_LIMIT = @"l";
NSString * const FindUsersRequest_KEY_FILTERED_USERS = @"fu";

@implementation FindUsersRequest



-(id)initWithExpr:(MatchExpression *)expr target:(id)target limit:(NSInteger)limit {

	if ((self = [super initWithId:BaseRequest_FindUsers])) {
		
		_matchExpr = expr;
		_target = target;
		_limit = limit;
		
	}
	
	return self;

}

+(id)requestWithExpr:(MatchExpression *)expr target:(id)target limit:(NSInteger)limit {
	FindUsersRequest *req = [[FindUsersRequest alloc] initWithExpr:expr target:target limit:limit];
	return req;
}

+(id)requestWithExpr:(MatchExpression *)expr {
	FindUsersRequest *req = [[FindUsersRequest alloc] initWithExpr:expr target:nil limit:0];
	return req;
}

-(void)validate:(SmartFox2XClient *)sfs {
	
	NSMutableArray *errors = [NSMutableArray array];
	
	if(_matchExpr == nil) {
		[errors addObject:@"Missing Match Expression"];
	}
	
	if ([errors count] > 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"FindUsers request error" errors:errors];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	[_sfso putSFSArray:FindUsersRequest_KEY_EXPRESSION value:[_matchExpr toSFSArray]];
	
	if (_target != nil) {
		
		if ([_target conformsToProtocol:@protocol(Room)]) {
			[_sfso putInt:FindUsersRequest_KEY_ROOM value:[(id <Room>)_target id]];
		}
		else if([_target isKindOfClass:[NSString class]]) {
			[_sfso putUtfString:FindUsersRequest_KEY_GROUP value:_target];
		}
		else {
			[[Logger getInstance] warn:[NSString stringWithFormat:@"Unsupport target type for FindUsersRequest: %@", _target]];
		}
		
	}
	
	if(_limit > 0) {
		[_sfso putShort:FindUsersRequest_KEY_LIMIT value:_limit];
	}
	
}



@end
