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

namespace MetaSite.Components.Controls.Views
{
	/// <summary>
	/// CreateUserData。
	/// </summary>
	[ToolboxItem(false),]
	public class CreateUserData : BaseTemplateControl
	{
		TextBox UserName;
		TextBox NickName;
		TextBox Password;
		TextBox Email;		
		CustomValidator   usernameValidator;
		CustomValidator   nickNameValidator;
		CustomValidator   passwordValidator;
		CustomValidator   CreateValidator;

		protected override void AttachChildControls()
		{			
			UserName = (TextBox) FindControl("UserName");			
			NickName = (TextBox) FindControl("NickName");			
			Password = (TextBox) FindControl("Password");	
			Email = (TextBox) FindControl("Email");			

			usernameValidator = (CustomValidator) FindControl("usernameValidator");
			nickNameValidator = (CustomValidator) FindControl("nickNameValidator");
			passwordValidator = (CustomValidator) FindControl("passwordValidator");
			CreateValidator = (CustomValidator) FindControl("CreateValidator");
			CreateValidator.ServerValidate += new ServerValidateEventHandler(ServerValidate);	
		
			//网页title
			Context.Items.Add(PageHead.key,"会员注册");
		}	
	
		private void ServerValidate(object source, ServerValidateEventArgs args)
		{
			UserCreateStatus status;

			string data =  UserName.Text; 

			if ( data.Length < 3 || data.Length > 20)
			{
                usernameValidator.IsValid = false;				
				usernameValidator.ErrorMessage = "帐户长度必须介于3-20位";
				return;
			}

			data = Password.Text;
 
			if (data.Length < Users.MinRequiredPasswordLength)
			{
				passwordValidator.IsValid = false;				
				passwordValidator.ErrorMessage = "密码长度必须大于"+Users.MinRequiredPasswordLength.ToString();
				return;
			}
   
			User u = Users.CreateUser(UserName.Text,NickName.Text,Password.Text, Email.Text,out status);
			
			if ( args.IsValid = (status == UserCreateStatus.Success)) 
			{
				ContextData.Current.User = u; 
				Roles.AddUserToRoles(u.UserName,new string[]{"Registered Users"});
				Page.Response.Redirect( Globals.ApplicationPath + "/default.aspx");  				
			}
			else
			{
				if ( status == UserCreateStatus.DuplicateEmail)
				{
					 usernameValidator.IsValid = false;				
				     usernameValidator.ErrorMessage = "用户已存在";
				}
				else if ( status == UserCreateStatus.DuplicateEmail)
				{
					 nickNameValidator.IsValid = false;				
					 nickNameValidator.ErrorMessage = " 呢称已存在";
				}
				else
					CreateValidator.ErrorMessage = "注册失败"; 
			}
		}
	}
}
