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

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer;
using CommunityServer.Components;

namespace CommunityServer.Controls 
{

    /// <summary>
    /// This Web control helps to change old user's password.
    /// </summary>
    [
    ParseChildren(true)
    ]
    public class ChangePassword : SecureTemplatedWebControl {

        #region Member variables and contructor
        CSContext csContext = CSContext.Current;

        protected TextBox					currentPassword;
        protected TextBox					newPassword1;
        protected TextBox					newPassword2;
        protected IButton					changePasswordButton;
        protected IText						userName;
		protected Control					showCurrentPassword;
		protected RequiredFieldValidator	currentPasswordValidator;
		protected RequiredFieldValidator	newPasswordValidator;
		protected RequiredFieldValidator	validatePassword2;
		protected CompareValidator			newPasswordCompareVadlidator;
        protected RegularExpressionValidator newPasswordRegExValidator;
        protected CustomValidator           newPasswordContentValidator;
        protected RegularExpressionValidator passwordRegExValidator;

        User user = null;

        // *********************************************************************
        //  ChangePassword
        //
        /// <summary>
        /// Constructor
        /// </summary>
        // ***********************************************************************/
        public ChangePassword() : base()  {
            if (csContext.UserID > 0 && csContext.User.IsAdministrator) {
                // Change passwd from admin
                user = Users.GetUser(csContext.UserID, true);
            } 
            else {
                // Change the user's password
                user = csContext.User;

                if(user.IsAnonymous)
                    Context.Response.Redirect(Globals.GetSiteUrls().Login);


            }
        }

        protected override string ExternalSkinFileName {
            get {
                if(SkinName != null)
                    return SkinName;
                else
                    return base.ExternalSkinFileName;
            }
            set {
                base.ExternalSkinFileName = value;
            }
        }

		private bool _isModal = false;
		public bool isModal
		{
			get { return _isModal; }
			set { _isModal = value; }
		}
        #endregion

        #region Initialize skin
        // *********************************************************************
        //  Initializeskin
        //
        /// <summary>
        /// Initialize the control template and populate the control with values
        /// </summary>
        // ***********************************************************************/
		protected override void AttachChildControls()
		{

            userName = FindText("UserName");
            if (csContext.UserID > 0 && (csContext.User.IsForumAdministrator || csContext.User.IsModerator) ) {
                userName.Text = "- (" + user.Username + ")";
            }

            // Find the textbox controls
            //
			if ( ((user.UserID != csContext.User.UserID) && (csContext.User.IsForumAdministrator || csContext.User.IsModerator) ) || csContext.Token != null ) {
				showCurrentPassword = FindControl("showCurrentPassword");
				showCurrentPassword.Visible = false;
			} else {
				showCurrentPassword =  FindControl("showCurrentPassword");
				showCurrentPassword.Visible = true;
				currentPassword = (TextBox) FindControl("Password");

                // LN 5/26/04: Get validator reference.
                currentPasswordValidator = (RequiredFieldValidator) FindControl("ValidatePassword");
                currentPasswordValidator.ErrorMessage = ResourceManager.GetString("ChangePassword_CurrentPasswordRequired");
			}

            newPassword1 = (TextBox) FindControl("NewPassword1");
            newPassword2 = (TextBox) FindControl("NewPassword2");

            // LN 5/26/04: Moved above on else condition.
            // Find the validators
            //
            /*
			if ( (user.UserID != Users.GetUser().UserID) && (forumContext.User.IsAdministrator || forumContext.User.IsModerator) ) {
				currentPasswordValidator = (RequiredFieldValidator) FindControl("ValidatePassword");
				currentPasswordValidator.ErrorMessage = ResourceManager.GetString("ChangePassword_CurrentPasswordRequired");
			}
            */
            passwordRegExValidator = FindControl("passwordRegExValidator") as RegularExpressionValidator;;
            passwordRegExValidator.ValidationExpression = csContext.SiteSettings.PasswordRegex;
            passwordRegExValidator.ErrorMessage = ResourceManager.GetString("ChangePassword_InvalidRegExContent");

            newPasswordValidator  = (RequiredFieldValidator) FindControl("ValidatePassword1");
            newPasswordValidator.ErrorMessage = ResourceManager.GetString("ChangePassword_NewPasswordRequired");

            newPasswordRegExValidator = FindControl("newPasswordRegExValidator") as RegularExpressionValidator;
            newPasswordRegExValidator.ValidationExpression = csContext.SiteSettings.PasswordRegex;
            newPasswordRegExValidator.ErrorMessage = ResourceManager.GetString("ChangePassword_InvalidRegExContent");
            
            newPasswordContentValidator = FindControl("newPasswordContentValidator") as CustomValidator;
            //newPasswordContentValidator.ErrorMessage = string.Format( ResourceManager.GetString("ChangePassword_InvalidLength"), ms.Membership.MinRequiredPasswordLength.ToString() );

            validatePassword2  = (RequiredFieldValidator) FindControl("ValidatePassword2");
            validatePassword2.ErrorMessage = ResourceManager.GetString("ChangePassword_ReEnterNewPasswordRequired");

            newPasswordCompareVadlidator = (CompareValidator) FindControl("ComparePassword");
            newPasswordCompareVadlidator.ErrorMessage = ResourceManager.GetString("ChangePassword_ReEnterNewPasswordInvalid");

            changePasswordButton = FindButton("ChangePasswordButton");
            changePasswordButton.Text = ResourceManager.GetString("ChangePassword_ChangePassword");
            changePasswordButton.Click += new EventHandler(ChangePassword_Click);

			// panic capture
			//
            if (csContext.User.IsForumAdministrator && csContext.UserID == 0)
                changePasswordButton.Attributes.Add("disabled","disabled");

        }
        #endregion

        #region Events
        void ChangePassword_Click (Object sender, EventArgs e) {
            bool status = false;
			string currentPass = "";

            if (!Page.IsValid)
                return;
            
            string errorMessage = "";
            if (!Users.PasswordIsMembershipCompliant( newPassword1.Text.Trim(), out errorMessage )) {
                newPasswordContentValidator.IsValid = false;
                newPasswordContentValidator.ErrorMessage = errorMessage;
                return;
            }

			if (currentPassword != null)
				if (currentPassword.Text != "")
					currentPass = currentPassword.Text;


                        
			if (user != null) {

				// Check if User account is locked before editing
				if (user.Member != null && user.Member.IsLockedOut == true)
				{
					StatusMessage message = FindControl("formStatus") as StatusMessage;
					if(message != null)
					{
						message.Success = false;
						message.Visible = true;
						message.ResourceName = "EditProfile_AccountLocked";
					}
					return;
				}

				user.Password = currentPass;
				status = user.ChangePassword(currentPass, newPassword1.Text);
			}

            if (status) {

				string returnUrl = csContext.ReturnUrl;
				if(Globals.IsNullorEmpty(returnUrl))
					returnUrl = Globals.GetSiteUrls().CleanUserEditProfile;

				if (isModal)
					Modal.ClosePage(this.Page);
				else
					LeaveSecureConnection(returnUrl);
			
                
            } else {
				StatusMessage message = FindControl("formStatus") as StatusMessage;
				if(message != null)
				{
					message.Success = false;
					message.Visible = true;
					message.ResourceName = "EditProfile_ChangePassword";
				}
                //throw new CSException( CSExceptionType.UserPasswordChangeFailed );
            }
        }
        #endregion
    }
}

