using System;
using System.Data;
using System.Web.UI.WebControls;
using ASPNET.StarterKit.TimeTracker.BusinessLogicLayer;

namespace ASPNET.StarterKit.TimeTracker.Web
{
	//*********************************************************************
	//
	// UserDetail.aspx
	//
	// The UserDetail.aspx page is used to add new user or make changes to
	// existing users.
	// In addition, user Roles are added and changed on this page.
	// Only members of the Admin Role can access this page.
	//
	//*********************************************************************

	public class UserDetail : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button Save;
		protected System.Web.UI.WebControls.Button Cancel;
		protected System.Web.UI.WebControls.TextBox	UserName;
		protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
		protected System.Web.UI.WebControls.DropDownList Roles;
		protected System.Web.UI.WebControls.Label lblError;
		protected System.Web.UI.WebControls.Label ErrorLabel;
		protected System.Web.UI.WebControls.Label ErrorLabel2;
		protected System.Web.UI.WebControls.Label userNamelbl;
		protected System.Web.UI.WebControls.Label rolelbl;
		protected System.Web.UI.WebControls.Label displayNamelbl;
		protected System.Web.UI.WebControls.TextBox DisplayName;
		protected System.Web.UI.WebControls.Label passwordlbl;
		protected System.Web.UI.WebControls.TextBox Password;
		protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator3;
		protected System.Web.UI.WebControls.Label confirmPasswordlbl;
		protected System.Web.UI.WebControls.TextBox ConfirmPassword;
		protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator4;
		protected System.Web.UI.WebControls.CompareValidator CompareValidator1;

		//Use TTUser component to capture user's input during edit mode
		private TTUser user = new TTUser();
		
		//*********************************************************
		//
		// UserDetail page of the Application
		//
		//*********************************************************

		private void Page_Load(object sender, System.EventArgs e)
		{
			// Ensure that the visiting user has access to view the current page
			if (TTSecurity.IsInRole(TTUser.UserRoleAdministrator) == false) 
			{
				Response.Redirect("AccessDenied.aspx?Index=-1", true);
			}

			if (!Page.IsPostBack)
			{
				BindInfo();

				//Hide fields for editing/adding windows authenticated users
				if ((user.Password == "" && user.UserID != 0) || (Context.User.Identity.AuthenticationType != "Forms" && user.UserID==0))
				{
					displayNamelbl.Visible = false;
                    DisplayName.Visible = false;
                    passwordlbl.Visible = false;
                    Password.Visible = false;
                    confirmPasswordlbl.Visible = false;
                    ConfirmPassword.Visible = false;
					RequiredFieldValidator3.Visible= false;
					RequiredFieldValidator4.Visible= false;
                    userNamelbl.Text = @"用户名 (格式： 域名或机器名\用户名 )";
				}
   			}
		}

		//*********************************************************************
		//
		// The BindInfo method retrieves the list of roles 
		// and Load User information if user exists
		//
		//*********************************************************************

		private void BindInfo()
		{	
			// Gets UserName from querystring
			// This value should by pass in by UserList.aspx
			string User = Request.QueryString["UserName"];

			Roles.DataSource = BusinessLogicLayer.Roles.GetRoles();
			Roles.DataTextField = "Name";
			Roles.DataValueField = "RoleID";
			Roles.DataBind();
			
			if (User != null)
			{
				user.UserName = User;
				user.Load();
				UserName.Text = user.UserName;
				UserName.ReadOnly = true;
				Roles.Items.FindByValue(user.Role).Selected = true;
				DisplayName.Text = user.DisplayName;
			}
			else
			{
				UserName.ReadOnly = false;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Save.Click += new System.EventHandler(this.Save_Click);
			this.Cancel.Click += new System.EventHandler(this.Cancel_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		//*********************************************************************
		//
		// The SaveButton_Click event handler saves the configuration of the user.
		// It updates if the current user id is not 0 and inserts if it is 0.
		//
		//*********************************************************************

		private void Save_Click(object sender, System.EventArgs e)
		{
			bool isUserFound = false;
			bool isUserActiveManager = false;

			// Save the user and ask the user object to make sure the username is
			// found in the user account source (NT SAM or Active Directory)
			user.UserName = TTSecurity.CleanStringRegex(UserName.Text);
			user.Load();
			user.Role = Roles.SelectedItem.Value;
			user.DisplayName = TTSecurity.CleanStringRegex(DisplayName.Text);
			if (Password.Text != string.Empty)
                user.Password = TTSecurity.Encrypt(Password.Text);
			user.Save(true, ref isUserFound, ref isUserActiveManager);

			// If we're adding a new user to the system and the username is not found in
			// the user account source (i.e. Active Directory or NT SAM), then we will
			// not allow the user to be added to our Time Tracker database.  Display an error
			// message so the user knows what happened.
			if (user.UserID == 0 && !isUserFound)
				ErrorLabel.Text = "用户名未找到";
			else if (isUserActiveManager)
				ErrorLabel.Text = "用户角色不能被改变，用户属于一或多个项目经理";
				
			else
				Response.Redirect("UserList.aspx?index=2&adminIndex=1", false);
		}

		//*********************************************************************
		//
		// The Cancel_Click event handler undo changes and redirect to UserList page
		//
		//*********************************************************************

		private void Cancel_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("UserList.aspx?index=2&adminIndex=1", false);
		}
	}
}
