/*
 * LoginController.j
 *
 * Created by Philippe Laval on 2009/03/19.
 * Copyright 2009 Philippe Laval. All rights reserved.
 */

@import <Foundation/CPObject.j>

@import <AppKit/CPWindowController.j>

@import "CPString_phpjs.j"


var loginControllerSharedInstance = nil;

@implementation LoginController : CPWindowController
{
	CPTextField userTextField;
	CPSecureTextField passwordTextField;
	CPSecureTextField confirmTextField;
	
	CPButton okButton;
	CPButton cancelButton;
	CPButton registerButton;
	
	BOOL isLoginIn @accessors(readonly);
	CPNumber accountID @accessors(readonly);
	
	CPURLConnection findConnection;
	CPURLConnection insertConnection;
}

+ (LoginController)sharedLoginController
{
	// debugger;
	
    if (loginControllerSharedInstance == nil)
    {
        loginControllerSharedInstance = [[LoginController alloc] init];
    }
    
    return loginControllerSharedInstance;
}

-(void)showLoginWindow:(id)sender
{
    var sharedLoginController = [LoginController sharedLoginController];
    [sharedLoginController showWindow:sender];
}

-(void)hideLoginWindow:(id)sender
{
    var sharedLoginController = [LoginController sharedLoginController];
    [[sharedLoginController window] orderOut:sender];
}

-(void)toggleLoginWindow:(id)sender 
{
	// debugger;
    var sharedLoginController = [LoginController sharedLoginController];
    var loginWindow = [sharedLoginController window];
    
  	if ([loginWindow isVisible] == YES) {
    	[loginWindow orderOut:sender];
  	}
  	else {
    	[sharedLoginController showWindow:sender];
  	}
}

- (id)init
{
	// Create the login window
    var theWindow = [[CPPanel alloc] initWithContentRect:CGRectMake(100,100,380,240) styleMask:CPHUDBackgroundWindowMask | CPClosableWindowMask | CPTitledWindowMask];
    self = [super initWithWindow:theWindow];
    if (self)
    {
		[theWindow setTitle:@"Login"];
		[theWindow setLevel:CPFloatingWindowLevel];
        
        [theWindow setDelegate:self];

		var contentView = [theWindow contentView];
		
		// Not login in
		isLoginIn = NO;
		accountID = -1;
		
		var textField = [[CPTextField alloc] initWithFrame:CGRectMake(10, 10, 360, 24)];
		[textField setObjectValue:@"Enter your email and password to login/register."];
		[textField setFont:[CPFont systemFontOfSize:12]];
		[textField setTextColor:[CPColor whiteColor]];
		[textField setAlignment:CPCenterTextAlignment];
		[contentView addSubview:textField]; 

		textField = [[CPTextField alloc] initWithFrame:CGRectMake(10, 40, 70, 24)];
		[textField setObjectValue:@"email:"];
		[textField setFont:[CPFont systemFontOfSize:12]];
		[textField setTextColor:[CPColor whiteColor]];
		[textField setAlignment:CPRightTextAlignment];
		[contentView addSubview:textField]; 

		textField = [[CPTextField alloc] initWithFrame:CGRectMake(10, 70, 70, 24)];
		[textField setObjectValue:@"password:"];
		[textField setFont:[CPFont systemFontOfSize:12]];
		[textField setTextColor:[CPColor whiteColor]];
		[textField setAlignment:CPRightTextAlignment];
		[contentView addSubview:textField]; 

		textField = [[CPTextField alloc] initWithFrame:CGRectMake(10, 100, 70, 24)];
		[textField setObjectValue:@"confirm:"];
		[textField setFont:[CPFont systemFontOfSize:12]];
		[textField setTextColor:[CPColor whiteColor]];
		[textField setAlignment:CPRightTextAlignment];
		[contentView addSubview:textField]; 

		// Add the fields
		userTextField = [[CPTextField alloc] initWithFrame:CGRectMake(100, 40, 250, 24)];
//		[userTextField setPlaceholderString:@"user"];
//		[userTextField setObjectValue:@"cool"];
		[userTextField setEditable:YES];
		[userTextField setSelectable:YES];
		// [userTextField setBordered:YES];
		[userTextField setDrawsBackground:YES];
		[userTextField setTextFieldBackgroundColor:[CPColor whiteColor]];
		[contentView addSubview:userTextField]; 
		
		passwordTextField = [[CPSecureTextField alloc] initWithFrame:CGRectMake(100, 70, 250, 24)];
		[passwordTextField setFont:[CPFont systemFontOfSize:12]];
		[contentView addSubview:passwordTextField]; 

		confirmTextField = [[CPSecureTextField alloc] initWithFrame:CGRectMake(100, 100, 250, 24)];
		[confirmTextField setFont:[CPFont systemFontOfSize:12]];
		[contentView addSubview:confirmTextField]; 
		
		okButton = [[CPButton alloc] initWithFrame:CGRectMake(270, 160, 80, 18)];
		[okButton setTitle:"Login"];
	    [okButton setAction:@selector(login:)];
	    [okButton setTarget:self];
		[contentView addSubview:okButton]; 
		
		cancelButton = [[CPButton alloc] initWithFrame:CGRectMake(180, 160, 80, 18)];
	    [cancelButton setAction:@selector(cancel:)];
	    [cancelButton setTarget:self];
		[cancelButton setTitle:"Cancel"];
		[contentView addSubview:cancelButton]; 

		registerButton = [[CPButton alloc] initWithFrame:CGRectMake(10, 160, 80, 18)];
		[registerButton setTitle:"Register"];
	    [registerButton setAction:@selector(register:)];
	    [registerButton setTarget:self];
		[contentView addSubview:registerButton]; 
	}
	
	return self;
}


-(void)logout:(id)sender
{
	// Not login in
	isLoginIn = NO;
	accountID = -1;
}

-(void)login:(id)sender
{
	debugger;
	
	if ([self checkEmail])
	{
		if ([self checkPassword])
		{
			if ([self checkPasswordLength:6])
			{
				// debugger;

				// Start a new connection with basic authentification
				var request = [self createFindRequestWithIdentifier:YES];
				findConnection = [CPURLConnection connectionWithRequest:request delegate:self]; 
			}
			else
			{
				// Show an error
				var message = [CPString stringWithFormat:"Password must have more than %d characters", 6];
				[self displayAlertWithMessage:message];
			}		
		}
		else
		{
			// Show an error
			[self displayAlertWithMessage:@"Password are different"];
		}
	}
	else
	{		
		// Show an error
		[self displayAlertWithMessage:@"Check your email (wrong format)"];		
	}
}

-(void)cancel:(id)sender
{
	[self hideLoginWindow:sender];
}

-(void)register:(id)sender
{
	debugger;
	
	if ([self checkEmail])
	{
		// Checks that the password are the same
		if ([self checkPassword])
		{
			if ([self checkPasswordLength:6])
			{
				// debugger;
			
				// Start a new connection with basic authentification
				var request = [self createInsertRequestWithIdentifier:YES];
				insertConnection = [CPURLConnection connectionWithRequest:request delegate:self]; 
			}
			else
			{
				// Show an error
				var message = [CPString stringWithFormat:"Password must have more than %d characters", 6];
				[self displayAlertWithMessage:message];
			}
		}
		else
		{
			// Show an error
			[self displayAlertWithMessage:@"Password are different"];
		}
	}
	else
	{
		// Show an error
		[self displayAlertWithMessage:@"Check your email (wrong format)"];		
	}
}

-(BOOL)checkEmail
{
	// Normalize the email to lower case (this will enable us to check the presence of accounts based to their email).
	var email = [[userTextField stringValue] lowercaseString];
	if ([email length] > 0)
	{
		// PLL : Cappuccino 0.6 : Warning the @ will not work in Objective-J => use RegExp instead
		// var re_email = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/ ;
		var re_email = new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$");
		
		return re_email.test(email);
	}
	
	return NO;
}

-(BOOL)checkPasswordLength:(int)length
{
	var password = [passwordTextField stringValue];
	
	return ([password length] >= length);
}

-(BOOL)checkPassword
{
	var password = [passwordTextField stringValue];
	var confirm = [confirmTextField stringValue];
	
	if ([password compare:confirm] == CPOrderedSame)
		return YES;
		
	return NO;
}


- (void)windowWillClose:(id)aSender
{
	// Update the menu state
}

@end


@implementation LoginController (URLRequest)

-(CPURLRequest)createJSONRequestWithIdentifier:(BOOL)useIndentifier
{
	// Create a javascript object from scratch
	var myFirstJSONObject = { "action" : "Login", "user" : "John", "password" : "Doe"};
      
	// Get the JSON representation of the object
	var content = [CPString JSONFromObject:myFirstJSONObject];
	var contentLength = [[CPString alloc] initWithFormat:@"%d", [content length]];
	
	debugger;

	var request = [[CPURLRequest alloc] initWithURL:@"http://macbookpro.local/~philippe/insert_account.php"]; 
	[request setHTTPMethod:@"POST"]; 
	[request setHTTPBody:content]; 
	[request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; 
	[request setValue:"text/plain;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
	if (useIndentifier)
	{
		var user = @"Aladdin";
		var password = @"open sesame";
		var secret = [[CPString stringWithFormat:@"%@:%@", user, password] encodeBase64];
		var authorization = [CPString stringWithFormat:@"Basic %@", secret];
	
		[request setValue:authorization forHTTPHeaderField:@"Authorization"]; 
	}
	
	return request;
} 


-(CPURLRequest)createInsertRequestWithIdentifier:(BOOL)useIndentifier
{
	// Normalize the email to lower case (this will enable us to check the presence of accounts based to their email).
	var email = [[userTextField stringValue] lowercaseString];
	// Password are keep with their case : ThisIsNotTheSame than thisIsNotTheSame
	var password = [passwordTextField stringValue];
	
	var content = [[CPString alloc] initWithFormat:@"email=%@&password=%@", 
						[email urlencode], 
						[password urlencode]];
	var contentLength = [[CPString alloc] initWithFormat:@"%d", [content length]];
	
	// debugger;

	var request = [[CPURLRequest alloc] initWithURL:@"http://macbookpro.local/~philippe/insert_account.php"]; 
	[request setHTTPMethod:@"POST"]; 
	[request setHTTPBody:content]; 
	[request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; 
	[request setValue:"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
	if (useIndentifier)
	{
		var serviceUser = @"Aladdin";
		var servicePassword = @"open sesame";
		var secret = [[CPString stringWithFormat:@"%@:%@", serviceUser, servicePassword] encodeBase64];
		var authorization = [CPString stringWithFormat:@"Basic %@", secret];
	
		[request setValue:authorization forHTTPHeaderField:@"Authorization"]; 
	}
	
	return request;
} 


-(CPURLRequest)createFindRequestWithIdentifier:(BOOL)useIndentifier
{
	// Normalize the email to lower case (this will enable us to check the presence of accounts based to their email).
	var email = [[userTextField stringValue] lowercaseString];
	// Password are keep with their case : ThisIsNotTheSame than thisIsNotTheSame
	var password = [passwordTextField stringValue];

	var content = [[CPString alloc] initWithFormat:@"email=%@&password=%@", 
						[email urlencode], 
						[password urlencode]];
	var contentLength = [[CPString alloc] initWithFormat:@"%d", [content length]];
	
	// debugger;

	var request = [[CPURLRequest alloc] initWithURL:@"http://macbookpro.local/~philippe/find_account.php"]; 
	[request setHTTPMethod:@"POST"]; 
	[request setHTTPBody:content]; 
	[request setValue:contentLength forHTTPHeaderField:@"Content-Length"]; 
	[request setValue:"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
	if (useIndentifier)
	{
		var serviceUser = @"Aladdin";
		var servicePassword = @"open sesame";
		var secret = [[CPString stringWithFormat:@"%@:%@", serviceUser, servicePassword] encodeBase64];
		var authorization = [CPString stringWithFormat:@"Basic %@", secret];
	
		[request setValue:authorization forHTTPHeaderField:@"Authorization"]; 
	}
	
	return request;
} 


-(void)connection:(CPURLConnection)connection didFailWithError:(id)error
{
	//debugger;
	[self displayAlertWithMessage:error];
}


-(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response
{
	//debugger;
	var statusCode = [response statusCode];
}

-(void)connection:(CPURLConnection)connection didReceiveData:(CPString)data
{
	debugger;
	var trimmedData = [data trim];
	
	// Create a javascript object from the JSON content 
	//receivedJsonData = [data objectFromJSON];
	
	if (connection == insertConnection)
	{
		// Check for errors
		if ([trimmedData caseInsensitiveCompare:@"Account already exist"] == CPOrderedSame)
		{
			// Report the error : an account found for this email already exist. The user need to login.
			[self displayAlertWithMessage:@"An account already exist for this email, please login."];
		}
		else
		{
			// We got our brand new account id
			accountID = [trimmedData intValue];
			isLoginIn = YES;
			
			[self hideLoginWindow:self];
		}
	}
	else if (connection == findConnection) 
	{
		// Check for errors
		if ([trimmedData caseInsensitiveCompare:@"The user need to register"] == CPOrderedSame)
		{
			// Report the error : no account found for this email
			[self displayAlertWithMessage:@"No account found, please register."];
		}
		else if ([trimmedData caseInsensitiveCompare:@"The user entered a wrong password"] == CPOrderedSame)
		{
			// Report the error : wrong password
			[self displayAlertWithMessage:@"Wrong password, verify your email/password."];
		}
		else
		{
			// We got our account id
			accountID = [trimmedData intValue];
			isLoginIn = YES;
			
			[self hideLoginWindow:self];
		}		
	}
	
}

-(void)connectionDidFinishLoading:(CPURLConnection)connection
{
	//debugger;
}

-(void)connectionDidReceiveAuthenticationChallenge:(CPURLConnection)connection
{
	debugger;

	// Stop the previous connection
	[connection cancel];

	// Start a new connection with basic authentification
	var request = [self createRequestWithIdentifier:YES];
	postConnection = [CPURLConnection connectionWithRequest:request delegate:self]; 
}

/* 
 * better use "trim" in the CPString category found in the file "CPString_phpjs.j"
 *
- (CPString)trimRight:(CPString)str
{
	debugger;
	
	var result = str;
	var index = [str length] - 1;
    
	while (1)
	{
		var character = result.charAt(index);
		if ((character === ' ') || (character === '\t') || (character === '\r') || (character === '\n'))
		{
			index--;
		}
		else
		{
			break;
		}
	}
   
	result = result.substr(0, index + 1);
   
	return result;
}
*/

@end


@implementation LoginController (Alert)

-(void)displayAlertWithMessage:(CPString)message
{
	var alert = [[CPAlert alloc] init];
	[alert setMessageText:message];
	[alert setAlertStyle:CPWarningAlertStyle]; 
	[alert addButtonWithTitle:@"OK"]
	[alert runModal];	
}

@end
