/* Copyright 2009 Palm, Inc.  All rights reserved. */

var ErrorAnalyzer = Class.create({ 
	initialize: function() { 
	}
});

ErrorAnalyzer.handleLoginErrorNotification = function(errorDetails) {
	Mojo.Log.info("Encountered login error: %j", errorDetails);
	
	if (ErrorAnalyzer.isCredentialRejected(errorDetails)) {
		errorDetails.errorTitle = $L("Login credentials rejected");
		errorDetails.errorMessage = $L("Tap to update your password");
		errorDetails.commandFunc = function() {
			if (errorDetails.account) {
				var sr = new Mojo.Service.Request('palm://com.palm.applicationManager', 
					{
			    		method: 'open',
					    parameters: {
							id: 'com.palm.app.email',
							// Note the account parameter is being forced into a string (with +"") because
							// it somehow gets corrupted when sent as a number
							params: { editAccount: true, account: errorDetails.account+"" }
						}
					});
			} else {
				Mojo.Log.error("Cannot show login edit scene due to invalid account =", errorDetails.account);
			}
		};
	} else if (ErrorAnalyzer.isWebLoginRequired(errorDetails)) {
		errorDetails.errorTitle = $L("Your Account is Locked");
		errorDetails.errorMessage = $L("Tap to unlock your account");
		var url = ErrorAnalyzer.getWebLoginURL(errorDetails);
		
		errorDetails.commandFunc = function() {
			// Open webpage
			var sr = new Mojo.Service.Request('palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					'id': 'com.palm.app.browser',
					'params': {scene: 'page', url: ErrorAnalyzer.getWebLoginURL(errorDetails)}
				}
			});
			
			// Reset login failed flag on account
			var clearSr = new Mojo.Service.Request('palm://com.palm.mail', {
				method: 'clearLoginFailed',
				parameters: {
					'account': errorDetails.account
				}
			});
		};
	} else { 
		errorDetails.errorTitle = errorDetails.accountName;
		errorDetails.errorMessage = $L("Unable To Sign In");
		
		errorDetails.commandFunc = function() {
			if (errorDetails.account && errorDetails.targetFolder) {
				var folderObj = { 
					folderId: errorDetails.targetFolder+"",
		            accountId: errorDetails.account
		        };
				var sr = new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {
						id: 'com.palm.app.email',
						// Note the account parameter is being forced into a string (with +"") because
						// it somehow gets corrupted when sent as a number
						params: { 
							'debounce': 'f'+ errorDetails.targetFolder, 
							'folderInfo': folderObj
						}
					}
				});
			} else {
				Mojo.Log.error("Cannot show list scene due to invalid account = %s, folder = %s", 
					errorDetails.account, errorDetails.targetFolder);
			}
		};
	} 
}

ErrorAnalyzer.analyzeLoginError = function(errorDetails) {
	if (ErrorAnalyzer.isCredentialRejected(errorDetails)) {
		return {
			"action": ErrorAnalyzer.kUpdateCredentialLEAction, 
			"reason": undefined
			};
	} else if (ErrorAnalyzer.isWebLoginRequired(errorDetails)) {
		return {
			"action": ErrorAnalyzer.kWebLoginRequiredLEAction, 
			"url": ErrorAnalyzer.getWebLoginURL(errorDetails)
			};
	} else {
		return {
			"action": ErrorAnalyzer.kUpdateCredentialLEAction, 
			"reason": ErrorAnalyzer.sanatizeServerResponse(errorDetails)
			};
	}
}

ErrorAnalyzer.isCredentialRejected = function(errorDetails) {
	if (!errorDetails || !errorDetails.reason) {
		// default to credential rejected error if we can't find any reason for login failure 
		Mojo.Log.info("Unable to find login reason from error details: %j", errorDetails);
		return true;
	}
	
	var reason = errorDetails.reason;
	return ErrorAnalyzer.kGmailCredentialsErrorPattern.test(reason) || ErrorAnalyzer.kYahooCredentialsErrorPattern.test(reason);
}

ErrorAnalyzer.isWebLoginRequired = function(errorDetails) {
	if (!errorDetails || !errorDetails.reason) {
		Mojo.Log.error("Unable to find login reason from error details: %j", errorDetails);
		return false;
	}
		
	var reason = errorDetails.reason;
	return ErrorAnalyzer.kYahooWebloginErrorPattern.test(reason)
			|| (errorDetails.accountDomain === $L("gmail") && ErrorAnalyzer.kGmailWebloginErrorPattern.test(reason));
}


ErrorAnalyzer.getWebLoginURL = function(errorDetails) {
	if (!errorDetails || !errorDetails.reason) {
		Mojo.Log.error("Unable to find login reason from error details: %j", errorDetails);
		return "";
	}
		
	var reason = errorDetails.reason;
	if (errorDetails.accountDomain === $L("gmail") && ErrorAnalyzer.kGmailWebloginErrorPattern.test(reason)) {
		if (errorDetails.accountLogin.indexOf($L("@gmail.com")) !== -1) 
			return ErrorAnalyzer.kGmailUnlockPage;
		else {
			var bizDomain = errorDetails.accountLogin.gsub(".*@", "");
			return ErrorAnalyzer.kGmailSMBAccountUnlockPage.interpolate({"domain": bizDomain});
		}
	}
	else if (ErrorAnalyzer.kYahooWebloginErrorPattern.test(reason)) 
		return ErrorAnalyzer.kYahooUnlockPage;
}

/**
 * For IMAP server responses, we need to strip out the prefix in the command response.
 * @param {Object} errorDetails
 */
ErrorAnalyzer.sanatizeServerResponse=function(errorDetails) {
	if (!errorDetails || !errorDetails.reason) 
		return undefined;
		
	var reason = errorDetails.reason;
	var pattern = /^~~A\d+ NO /;
	return reason.replace(pattern, "");
}

ErrorAnalyzer.kUpdateCredentialLEAction = "updateCredential";
ErrorAnalyzer.kWebLoginRequiredLEAction = "webLoginRequired";

ErrorAnalyzer.kEASCredentialsErrorPattern = /^bad login\/password$/;
ErrorAnalyzer.kGmailWebloginErrorPattern = /^~~A\d+ NO .*Web login required.*$/;
ErrorAnalyzer.kGmailCredentialsErrorPattern = /^~~A\d+ NO .*Invalid credentials.*$/;
ErrorAnalyzer.kYahooWebloginErrorPattern = /^Invalid security token: .*\r\n(1213|1218)\r\n\d\r\n\r\n/;  
ErrorAnalyzer.kYahooCredentialsErrorPattern = /(^Invalid security token: .*\r\n(1212|1235)\r\n\d\r\n\r\n|^Missing crumb in response: .*)/;
	
ErrorAnalyzer.kGmailUnlockPage = "https://www.google.com/accounts/DisplayUnlockCaptcha";
ErrorAnalyzer.kGmailSMBAccountUnlockPage = "https://www.google.com/a/#{domain}/UnlockCaptcha";
ErrorAnalyzer.kYahooUnlockPage = "http://mail.yahoo.com";
