//
//  LoginRequest.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 "LoginRequest.h"
#import "SmartFox2XClient.h"
#import "ConfigData.h"
#import "Categories.h"

NSString * const LoginRequest_KEY_ZONE_NAME = @"zn";
NSString * const LoginRequest_KEY_USER_NAME = @"un";
NSString * const LoginRequest_KEY_PASSWORD = @"pw";
NSString * const LoginRequest_KEY_PARAMS = @"p";
NSString * const LoginRequest_KEY_PRIVILEGE_ID = @"pi";
NSString * const LoginRequest_KEY_ID = @"id";
NSString * const LoginRequest_KEY_ROOMLIST = @"rl";
NSString * const LoginRequest_KEY_RECONNECTION_SECONDS = @"rs";

@implementation LoginRequest

@synthesize zoneName = _zoneName;
@synthesize userName = _userName;
@synthesize password = _password;
@synthesize params = _params;


-(id)initWithUserName:(NSString *)userName password:(NSString *)password zoneName:(NSString *)zoneName params:(id <ISFSObject>)params {
	
	if ((self = [super initWithId:BaseRequest_Login])) {
		
		self.zoneName = zoneName;
		self.userName = userName;
		self.password = (password == nil) ? [NSString string] : password;
		self.params = params;
				
	}
	
	return self;
	
}

+(id)requestWithUserName:(NSString *)userName password:(NSString *)password zoneName:(NSString *)zoneName params:(id <ISFSObject>)params {

	LoginRequest *req = [[LoginRequest alloc] initWithUserName:userName password:password zoneName:zoneName params:params];
	return req;
}

+(id)request {
	LoginRequest *req = [[LoginRequest alloc] initWithUserName:@"" password:@"" zoneName:@"" params:nil];
	return req;
}

-(void)validate:(SmartFox2XClient *)sfs {
	
	if (sfs.mySelf != nil) {
		@throw [SFSValidationException validationExceptionWithReason:@"LoginRequest Error" errors:[NSMutableArray arrayWithObjects:@"You are already logged in. Logout first", nil]];
	}
	
	if ((_zoneName == nil || [_zoneName length] == 0) && sfs.config != nil) {
		
		self.zoneName = sfs.config.zone;
	}
	
	if (_zoneName == nil || [_zoneName length] == 0) {
		@throw [SFSValidationException validationExceptionWithReason:@"LoginRequest Error" errors:[NSMutableArray arrayWithObjects:@"Missing Zone name", nil]];
	}
}


-(void)execute:(SmartFox2XClient *)sfs{
	
	[_sfso putUtfString:LoginRequest_KEY_ZONE_NAME value:_zoneName];
	[_sfso putUtfString:LoginRequest_KEY_USER_NAME value:_userName];
	
	if ([_password length] > 0) {
		self.password = [[NSString stringWithFormat:@"%@%@", sfs.sessionToken, _password] md5];
	}
	
	[_sfso putUtfString:LoginRequest_KEY_PASSWORD value:_password];
	
	if (_params != nil) {
		[_sfso putSFSObject:LoginRequest_KEY_PARAMS value:_params];
	}
}



@end
