#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
// 
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at SourceForge at http://sourceforge.net/projects/subtext
// The development mailing list is at subtext-devs@lists.sourceforge.net 
//
// This project is licensed under the BSD license.  See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Configuration;
using Subtext.Extensibility.Providers;
using Subtext.Framework;
using Subtext.Framework.Configuration;
using Subtext.Framework.Text;
using log4net;
using Subtext.Framework.Security;

namespace Subtext.Web.Pages
{
	/// <summary>
	/// Summary description for login.
	/// </summary>
	public partial class login : System.Web.UI.Page
	{
		private readonly static ILog log = new Subtext.Framework.Logging.Log();

		#region Declared Controls
		#endregion
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
		}

		#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()
		{    

		}
		#endregion

		protected void lbSendPassword_Click(object sender, System.EventArgs e)
		{
			BlogInfo info = Config.CurrentBlog;
			bool messageSent = false;
			string password;
			
			if(info != null)
			{
				//Try Admin login.
				if (String.Equals(tbUserName.Text, info.UserName, StringComparison.InvariantCultureIgnoreCase))
				{
					if(info.IsPasswordHashed)
					{
						password = SecurityHelper.ResetPassword();
					}
					else
					{
						password = info.Password;
					}

                    log.Warn(info.UserName + "管理密码被重新设定");
					
					string message = "Here is your blog login information:\nUserName: {0}\nPassword: {1}\n\nNote: your old password will no longer work.";
					EmailProvider mail = Subtext.Extensibility.Providers.EmailProvider.Instance();
			
					string To = info.Email;
					string From = mail.AdminEmail;
					string Subject = "Login Credentials";
					string Body = string.Format(message,info.UserName,password);
					mail.Send(To,From,Subject,Body);
					Message.Text = "Login Credentials Sent<br />";
					messageSent = true;
				}
			}

			if (String.Equals(tbUserName.Text, HostInfo.Instance.HostUserName, StringComparison.InvariantCultureIgnoreCase))
			{
				//Try Host Admin login.
				if(Config.Settings.UseHashedPasswords)
					password = SecurityHelper.ResetHostAdminPassword();		
				else
					password = HostInfo.Instance.Password;

                log.Warn("HostAdmin密码被重新设定" + HostInfo.Instance.HostUserName);

                string message = "你的HostAdmin登录数据为:\n用户名: {0}\n密码: {1}\n\n如果你没有请求它，请忽视这一个信息.";
				EmailProvider mail = Subtext.Extensibility.Providers.EmailProvider.Instance();
			
				string hostAdminEmail = ConfigurationManager.AppSettings["HostEmailAddress"];
				if(hostAdminEmail == null || hostAdminEmail.Length == 0 || hostAdminEmail.IndexOf('@') <= 0) //Need better email validation. I know!
				{
					log.Debug("请在Web.config中指定管理员邮件地址");
					Message.Text = "Sorry, but I don&#8217;t know where to send the email.  Please specify a Host Email Address in Web.config. It is the AppSetting &#8220;HostEmailAddress&#8221;";
					return;
				}
				string To = hostAdminEmail;
				string From = mail.AdminEmail;
				string Subject = "Subtext Host Admin Login Credentials";
				string Body = string.Format(message, HostInfo.Instance.HostUserName, password);
				mail.Send(To, From, Subject, Body);
				Message.Text = "Login Credentials Sent<br />";
				messageSent = true;
			}
			
			if(!messageSent)
			{
                log.Warn("失败的请求重新设定密码 " + tbUserName.Text);
				Message.Text = "I don't know you";
			}
		}

		protected void btnLogin_Click(object sender, System.EventArgs e)
		{
			BlogInfo currentBlog = Config.CurrentBlog;
			string returnUrl = Request.QueryString["ReturnURL"];
			if(currentBlog == null || (returnUrl != null && StringHelper.Contains(returnUrl, "HostAdmin", StringComparison.InvariantCultureIgnoreCase)))
			{
				if(!AuthenticateHostAdmin())
				{
					log.Warn("HostAdmin 登录失败 " + tbUserName.Text);
                    Message.Text = "登录失败<br />";
					return;
				}
				else
				{
					ReturnToUrl("~/HostAdmin/Default.aspx");
					return;
				}
			}
			else
			{
				if(SecurityHelper.Authenticate(tbUserName.Text, tbPassword.Text, chkRemember.Checked))
				{
					ReturnToUrl(currentBlog.AdminHomeVirtualUrl);
					return;
				}
				else
				{
                    log.Warn("管理登录失败 " + tbUserName.Text);
                    Message.Text = "登录失败<br />";
				}
			}
		}
		
		private void ReturnToUrl(string defaultReturnUrl)
		{
			if(Request.QueryString["ReturnURL"] != null && Request.QueryString["ReturnURL"].Length > 0)
			{
                log.Debug("重新转到 " + Request.QueryString["ReturnURL"]);
				Response.Redirect(Request.QueryString["ReturnURL"], false);
				return;
			}
			else
			{
                log.Debug("重新转到 " + defaultReturnUrl);
				Response.Redirect(defaultReturnUrl, false);
				return;
			}
		}

		private bool AuthenticateHostAdmin()
		{
			return SecurityHelper.AuthenticateHostAdmin(tbUserName.Text, tbPassword.Text, chkRemember.Checked);
		}
	}
}