using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace VoServices.Footprint.Web
{
	/// <summary>
	/// Summary description for _default.
	/// </summary>
	public partial class login : BasePageTemplated
	{
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			TitleLabel.Text = "User login";
		}

		#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.PasswordValidator.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(this.PasswordValidator_ServerValidate);

		}
		#endregion

		protected void Ok_Click(object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				Response.Redirect("../default.aspx");
			}
		}

		private void PasswordValidator_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
		{
			try
			{
				User usr = new User(DatabaseConnection);
				usr.Username = UserId.Text;
				usr.Password = Password.Text;

				bool res = usr.Login();

				if (res)
				{
					Session["UserWebServiceId"] = usr.Guid;
					Session["UserName"] = usr.Username;
				}
				else
				{
					PasswordValidator.Text = "Invalid username or password.";
					Session["UserWebServiceId"] = "";
					Session["UserName"] = "";
				}

				args.IsValid = res;
			}
			catch (System.Exception ex)
			{
				PasswordValidator.Text = "Login failed.";
				Session["UserWebServiceId"] = "";
				Session["UserName"] = "";
				args.IsValid = false;
			}
		}
	}
}
