using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Bitrix.UI;
using Bitrix.Services;
using Bitrix.Security;
using System.Data.SqlClient;
using Bitrix.Configuration;
using System.Reflection;
using Bitrix.Installer;
using System.Text.RegularExpressions;


public partial class bitrix_install_Step6 : BXWizardStep
{
	string MakeHiddenText(string id, string text)
	{
		return string.Format(
@"
<div>
	<a href=""#"" onclick=""javascript:var div = document.getElementById('{0}'); div.style.display = (div.style.display == 'none') ? 'block' : 'none';"" style=""font-size: 8px"" >{2}<a/>
	<div id=""{0}"" style=""display: none; border: solid; padding: 5px; overflow: auto; width: 450px"">
		<pre>{1}</pre>
	</div>
</div>",
			id, 
			HttpUtility.HtmlEncode(text),
			BXInstaller.GetMessage(this, "Details")
		);
	}
	
	protected void Page_Load(object sender, EventArgs e)
    {

    }

	protected bool IsValidEmail(string strIn)
	{
		return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
	}

    protected override void OnNext(object sender, EventArgs arg)
    {
		if (!Page.IsValid)
			return;
		
		string connectionString = ConfigurationManager.ConnectionStrings["BXConnectionString"].ConnectionString + ";MultipleActiveResultSets = true;";
		using (SqlConnection conn = new SqlConnection(connectionString))
		{
			conn.Open();

			bool dbExists = true;
			SqlCommand command = new SqlCommand("SELECT 1 FROM b_Modules", conn);
			SqlDataReader reader = null;
			try
			{
				reader = command.ExecuteReader();
			}
			catch
			{
				dbExists = false;
			}

			if (dbExists)
			{
				try
				{
					reader.Close();
					conn.Close();
				}
				catch
				{
					dbExists = false;
				}
			}
			else
			{
				try
				{
					BXInstaller.RestoreDb(connectionString);
				}
				catch (Exception ex)
				{
					Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.DBFillError") + MakeHiddenText("detail_exception", ex.ToString()));
					return;
				}
			}
		}

		try
        {
            BXUser admin = BXUserManager.GetById(1, false);
            admin.Email = txtEmail.Text;
            admin.FirstName = txtName.Text;
            admin.LastName = txtSurname.Text;
            admin.Update();
            if (!BXUserManager.ChangePassword(1, "!!!!!!!", txtPassword.Text))
				throw new Exception("Unable to change password.");
        }
        catch (Exception ex)
        {
           Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToChangeAdminPassword") + MakeHiddenText("detail_exception", ex.ToString()));
           return;
        }

		string ajaxVer = "1.0.61025.0";
		try
		{
			Assembly ajax = Assembly.Load("System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
			if (ajax != null)
			{
				ajaxVer = "3.5.0.0";
			}
		}
		catch
		{
		}		



        BXWebConfig config = new BXWebConfig();
        config.Load(MapPath("~/web.config"));
		string path = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
		if (!path.EndsWith("/"))
			path += "/";
		if (path != "/")
			BXInstaller.InstallCookiePath(config, path);
        BXInstaller.InstallHttpModules(config, ajaxVer);
        BXInstaller.InstallAjax(config, ajaxVer);
		BXInstaller.InstallMachineKey(config);
		BXInstaller.InstallGlobalAsax(MapPath("~/Global.bitasax"));
        
        config.Save();

		string providerName = null;
		if (BXAuthentication.Authenticate("admin", txtPassword.Text, out providerName))
			BXAuthentication.SetAuthCookie("admin", providerName, false);

        BXInstaller.RegisterAgent(connectionString);

        base.OnNext(sender, arg);
    }

	protected void ValidatePassword(object sender, ServerValidateEventArgs e)
	{
		e.IsValid = false;

		if (e.Value.Length < 7)
			return;

		for (int i = 0; i < e.Value.Length; i++)
			if (!char.IsLetterOrDigit(e.Value, i))
			{
				e.IsValid = true;
				return;
			}
	}
}
