//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;

namespace CommunityServer.ControlPanel.Membership
{
	/// <summary>
	/// This page displays the textboxes needed to create a new user account.
	/// The user can enter their username and email, and a warning message is displayed if
	/// either the username or email message is already taken.  Once the user enters an available
	/// username and password, they will be sent a confirmation email with their password.
	/// </summary>
	public class UserAdd : BaseMembershipPage
	{

		#region Members

		protected TextBox username;
		protected TextBox password;
		protected TextBox password2;
		protected TextBox email;
		protected RequiredFieldValidator usernameValidator;
		protected RegularExpressionValidator usernameRegExValidator;
		protected CustomValidator usernameLengthValidator;

		protected RequiredFieldValidator placeHolderValidator;

		protected RequiredFieldValidator passwordValidator;
		protected RegularExpressionValidator passwordRegExValidator;
		protected CustomValidator passwordContentValidator;
		protected RequiredFieldValidator password2Validator;
		protected CompareValidator comparePassword;

		protected RequiredFieldValidator emailValidator;
		protected RegularExpressionValidator emailRegExValidator;

		protected TimezoneDropDownList timezone;
		protected ResourceLinkButton createButton;
		protected ValidationSummary validationSummary;

		bool passportAuthentication = false;
		protected ResourceControl Resourcecontrol1;
		protected MPContent DescriptionRegion;
		protected HelpIcon Helpicon2;
		protected ResourceControl Resourcecontrol2;
		protected HelpIcon Helpicon1;
		protected ResourceControl Resourcecontrol3;
		protected ResourceControl Resourcecontrol4;
		protected HelpIcon Helpicon4;
		protected ResourceControl Resourcecontrol5;
		protected HelpIcon Helpicon3;
		protected ResourceControl Resourcecontrol8;
		protected MPContent TaskRegion;
		protected MPContainer MPContainer;
		CSContext csContext = CSContext.Current;

		#endregion

		override protected void OnInit(EventArgs e)
		{

			createButton.Click += new EventHandler(createButton_Click);

			usernameRegExValidator.ValidationExpression = csContext.SiteSettings.UsernameRegex;            
			usernameValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_usernameValidator").Replace("'", @"\'");
			usernameRegExValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_usernameRegExValidator").Replace("'", @"\'");
			usernameLengthValidator.ErrorMessage = string.Format(ResourceManager.GetString("CreateNewAccount_UsernameLimits"), csContext.SiteSettings.UsernameMinLength.ToString(), csContext.SiteSettings.UsernameMaxLength.ToString());

			passwordRegExValidator.ValidationExpression = csContext.SiteSettings.PasswordRegex;
			passwordValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_passwordValidator").Replace("'", @"\'");
			passwordRegExValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_PasswordRegExValidator").Replace("'", @"\'");;
			comparePassword.ErrorMessage = ResourceManager.GetString("ChangePassword_ReEnterNewPasswordRequired").Replace("'", @"\'");
			password2Validator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_passwordValidator").Replace("'", @"\'");

			emailRegExValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_emailRegExValidator").Replace("'", @"\'");
			emailValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_emailValidator").Replace("'", @"\'");

			this.Load += new EventHandler(this.Page_Load);

			base.OnInit(e);
		}
		

		private void Page_Load(object sender, EventArgs e)
		{
			if(Context.User.Identity.AuthenticationType.ToLower() == "passport")
				passportAuthentication = true;

		
			if(!Page.IsPostBack && !this.IsCallBack)
			{
				Bind();
			}

		}

		private void Bind()
		{
			string serverTimeZone = csContext.SiteSettings.TimezoneOffset.ToString();
			if (timezone.Items.FindByValue(serverTimeZone) != null)
				timezone.Items.FindByValue(serverTimeZone).Selected = true;
			else if (timezone.Items.FindByValue("0") != null)
				timezone.Items.FindByValue("0").Selected = true;

		}


		private void createButton_Click(Object sender, EventArgs e) 
		{
			CreateUserStatus status = CreateUserStatus.UnknownFailure;
			
			// Is valid?
			if (!Page.IsValid)
				return;

			// Check the max length on the signature
			if ((username.Text.Length > CSContext.Current.SiteSettings.UsernameMaxLength) || (username.Text.Length < csContext.SiteSettings.UsernameMinLength)) 
			{
				usernameLengthValidator.IsValid = false;
				return;
			}

			string errorMessage = "";

			if (!passportAuthentication) 
			{
				if (!Users.PasswordIsMembershipCompliant( password.Text.Trim(), out errorMessage )) 
				{
					passwordContentValidator.IsValid = false;
					passwordContentValidator.ErrorMessage = errorMessage;
					return;
				}
			}

			// Reset the placeHolderValidator
			placeHolderValidator.IsValid = true;

			// try to create the new user account
			User user = new User();
			user.Username = username.Text;			
			user.Email = email.Text;
			user.Password = password.Text.Trim();
			//user.PasswordFormat = CSContext.Current.SiteSettings.PasswordFormat;
			user.AccountStatus = UserAccountStatus.Approved;
			user.IsAnonymous = false;

			// Passport authentication
			if(passportAuthentication && Context.Items.Contains("PassportUID"))
			{
				user.AppUserToken = (string)Context.Items["PassportUID"];
				user.Password = user.AppUserToken;
			}

			// Attempt to create the user
			if (user.Username == "Anonymous") 
			{
				status = CreateUserStatus.DuplicateUsername;
			} 
			else 
			{

				try 
				{
					status = Users.Create(user, true, CSContext.Current.User.IsAdministrator);
				}
				catch (CSException exception)
				{
					status = exception.CreateUserStatus;
				}
                catch(Exception ex)
                {
                    status = MemberRoleProfileProvider.Instance().Members.GetCreateUserStatus(ex);
                }

			}

			// Determine if the account was created successfully
			switch (status) 
			{
					// Username is disallowed
				case CreateUserStatus.DisallowedUsername:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_DisallowedUsername");
					placeHolderValidator.IsValid = false;
					break;

					// Username already exists!
				case CreateUserStatus.DuplicateUsername:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_DuplicateUsername");
					placeHolderValidator.IsValid = false;
					break;

					// Email already exists!
				case CreateUserStatus.DuplicateEmailAddress:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_DuplicateEmailAddress");
					placeHolderValidator.IsValid = false;
					break;

				case CreateUserStatus.InvalidEmail:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_InvalidEmail");
					placeHolderValidator.IsValid = false;
					break;

				case CreateUserStatus.InvalidPassword:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_InvalidPassword");
					placeHolderValidator.IsValid = false;
					break;

				case CreateUserStatus.InvalidQuestionAnswer:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_QA");
					placeHolderValidator.IsValid = false;
					break;

				case CreateUserStatus.InvalidUserName:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_InvalidUserName");
					placeHolderValidator.IsValid = false;
					break;
					
					// Unknown failure has occurred!
				case CreateUserStatus.UnknownFailure:
					placeHolderValidator.ErrorMessage = ResourceManager.GetString("CreateNewAccount_CreateUserStatus_UnknownFailure");
					placeHolderValidator.IsValid = false;
					break;
					
					// Everything went off fine, good
				case CreateUserStatus.Created:
					SaveAdditionalProfileData(user);
					Response.Redirect(SiteUrls.Instance().ControlPanelUserAddedMessage(user.UserID));
					break;
			}			

		}

		private void InitializeComponent()
		{
		
		}

		private void SaveAdditionalProfileData(User user)
		{
			if (timezone != null)
				user.Profile.Timezone = double.Parse(timezone.SelectedItem.Value);

			Users.UpdateUser(user);
		}



	}
}
