using System;
using System.Web.UI.WebControls;   
using Meta.Web.Controls.Template;   
using Meta.Web.Security; 
using Meta.Web;

using MetaSite.Components.Providers; 

namespace MetaSite.Components.Controls.Views
{
	/// <summary>
	/// ChangePassword。
	/// </summary>
	public class ChangePassword : BaseTemplateControl
	{		
		Label UserInfo;
		Label lold;
		TextBox txtOld;
		TextBox txtNew;
		TextBox txtRnew;
		Button btOk; 
		bool IsLoginUser = false;
		ContextData context;
		CustomValidator Valiold;
		CustomValidator Valinewpass;		

		protected override void AttachChildControls()
		{
			context = ContextData.Current; 
			if( !(IsLoginUser = (context.User.UserId == context.GetIntFromQueryString("userid",-1))))
			{
				if ( !AdminSettings.InAdminRoles("ManageUser"))
				{
					ForumPermission.RedirectOrExcpetion();			
				}
			}
 
			txtOld = (TextBox) FindControl("txtOld");	
			txtNew = (TextBox) FindControl("txtNew");	
			txtRnew = (TextBox) FindControl("txtRnew");
			UserInfo = (Label) FindControl("UserInfo");	
			lold = (Label) FindControl("lold");	
			btOk = (Button) FindControl("btOk");
			Valiold = (CustomValidator) FindControl("Valiold");
			Valinewpass = (CustomValidator) FindControl("Valinewpass");
			
			Valiold.ServerValidate += new ServerValidateEventHandler(Valiold_ServerValidate); 
			Valinewpass.ServerValidate += new ServerValidateEventHandler(Valiold_ServerValidate); 
			
			btOk.Click += new EventHandler(btOk_Click);

			UserInfo.Text += "["+context.UserName+"]"; 

			if ( !IsLoginUser)
			{
				lold.Visible = false;
				txtOld.Visible = false;
			}

			Context.Items.Add(PageHead.key,"更改密码");
		}

		private void btOk_Click(object sender, EventArgs e)
		{
            //UsersProvider.Updatepassword(context.User.UserId,txtNew.Text);     						
		}

		private void Valiold_ServerValidate(object source, ServerValidateEventArgs args)
		{			

			if (IsLoginUser)
			{
				if ( Valiold.IsValid  = (!txtOld.Text.Equals("")))
				{
					if( !(Valiold.IsValid = Users.ValidateUser( context.UserName,txtOld.Text)))
					{
						Valiold.ErrorMessage = "旧密码输入不正确";
					}
				}
				else
				{
                    Valiold.ErrorMessage = "未设置旧密码";
				}
			}		
			
			if (txtNew.Text.Length < Users.MinRequiredPasswordLength)
			{
				Valinewpass.IsValid = false;				
				Valinewpass.ErrorMessage = "密码长度必须大于"+Users.MinRequiredPasswordLength.ToString();				
			}
			
			if ( Valiold.IsValid && Valinewpass.IsValid )
			{
				UsersProvider.Updatepassword(context.User.UserId,txtNew.Text);     		
			}
		}
	}
}
