using System;
using System.Data;
using System.Data.SqlClient;
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.Configuration;
using Bitrix.Installer;

public partial class bitrix_install_Step5 : BXWizardStep
{
	const string connectionStringIS = "Data Source={0};Integrated Security = True";
	const string connectionString = "Data Source={0};Integrated Security = False;User ID={1};Password={2};";
	const string createDataBase = "CREATE DATABASE [{0}] ";
	const string connectionStringFull = "Data Source={0};Integrated Security = False;User ID={1};Password={2};Initial Catalog={3};";

	protected void Page_Load(object sender, EventArgs e)
	{

	}


	protected override void OnNext(object sender, EventArgs arg)
	{
		if (!Page.IsValid)
			return;
		
		BXWebConfig config = new BXWebConfig();
		config.Load(MapPath("~/web.config"));

		//SELECT USER
		string userLogin;
		string userPassword;

		if (!UserExists.Checked || !DbExists.Checked)
		{
			userLogin = txtAdminLogin.Text;
			userPassword = string.IsNullOrEmpty(txtAdminPass.Text) ? "" : txtAdminPass.Text;

			if (string.IsNullOrEmpty(userLogin))
			{
				Errors.AddErrorHtml(
					!UserExists.Checked
					? BXInstaller.GetMessage(this, "Error.AdminRequiredToCreateUser")
					: BXInstaller.GetMessage(this, "Error.AdminRequiredToCreateDB")
				);

				return;
			}
		}
		else
		{
			if (txtAdminLogin.Text.Length > 0)
			{
				userLogin = txtAdminLogin.Text;
				userPassword = txtAdminPass.Text;
			}
			else
			{
				userLogin = txtUserLogin.Text;
				userPassword = txtUserPass.Text;
			}
		}


		//CHECK DB SERVER CONNECTION
		string connectionStringServer = string.Format(connectionString, txtServer.Text, userLogin, userPassword);
		if (!BXInstaller.CheckConnection(connectionStringServer))
		{
			Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToConnectToServer"));
			return;
		}

		//CREATE DB
		string connectionStringDB = string.Format(connectionStringFull, txtServer.Text, userLogin, userPassword, txtDbName.Text);
		if (DbExists.Checked)
		{
			if (!BXInstaller.CheckConnection(connectionStringDB))
			{
				Errors.AddErrorHtml(string.Format(BXInstaller.GetMessage(this, "Error.UnableToConnectToDB"), HttpUtility.HtmlEncode(txtDbName.Text)));
				return;
			}
		}
		else
		{
			if (BXInstaller.CheckConnection(connectionStringDB))
			{
				Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.DBAlreadyExists"));
				return;
			}

			try
			{
				BXInstaller.CreateDb(connectionStringServer, txtDbName.Text);
			}
			catch
			{
				Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToCreateDB"));
				return;
			}
		}


		if (!UserExists.Checked)
		{
			userLogin = txtAdminLogin.Text;
			userPassword = txtAdminPass.Text;

			try
			{
				BXInstaller.CreateDbUser(connectionStringServer, txtUserLogin.Text, txtUserPass.Text);
			}
			catch (Exception ex)
			{
				Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToCreateUser") + HttpUtility.HtmlEncode(ex.Message));
				return;
			}

		}
		else
		{
			userLogin = txtUserLogin.Text;
			userPassword = txtUserPass.Text;
		}

		if (txtUserLogin.Text != "sa")
		{
			try
			{
				BXInstaller.SetDbUser(connectionStringServer, txtUserLogin.Text, txtDbName.Text);
			}
			catch //(Exception ex)
			{
				//ErrorMsg.Visible = true;
				//ErrorText.Text = "Не удалось создать пользователя."+ex.Message;
				//return;
			}
		}

		try
		{
			BXInstaller.InstallConnectionString(config, string.Format(connectionStringFull, txtServer.Text, txtUserLogin.Text, txtUserPass.Text, txtDbName.Text));
		}
		catch
		{
			Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToStoreConnectionString"));
			return;
		}


		try
		{
			//BXInstaller.AlterCollationDb(string.Format(connectionStringFull, txtServer.Text, txtUserLogin.Text, txtUserPass.Text, txtDbName.Text) + "Timeout=1000;", txtDbName.Text);	
			string dbConnectionString = string.Format(connectionStringFull, txtServer.Text, txtUserLogin.Text, txtUserPass.Text, txtDbName.Text) + "Timeout=1000;";
			string dbName = txtDbName.Text;
			SqlConnection conn = null;
			try
			{
				conn = new SqlConnection(dbConnectionString);
				conn.Open();
				using (SqlCommand cmd = new SqlCommand(string.Format(
					@"ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;", dbName), conn))
					cmd.ExecuteNonQuery();
			}
			catch (Exception)
			{
				throw;
			}
			finally
			{
				if (conn != null)
				{
					conn.Close();
					SqlConnection.ClearPool(conn);
				}
			}

			try
			{
				conn = new SqlConnection(dbConnectionString);
				conn.Open();
				using (SqlCommand cmd = new SqlCommand(string.Format(
					@"ALTER DATABASE [{0}] COLLATE SQL_Latin1_General_CP1251_CI_AS;", dbName), conn))
					cmd.ExecuteNonQuery();
			}
			catch (Exception)
			{
				throw;
			}
			finally
			{
				if (conn != null)
				{
					conn.Close();
					SqlConnection.ClearPool(conn);
				}
			}

			try
			{
				conn = new SqlConnection(dbConnectionString);
				conn.Open();
				using (SqlCommand cmd = new SqlCommand(string.Format(
					@"ALTER DATABASE [{0}] SET MULTI_USER;", dbName), conn))
					cmd.ExecuteNonQuery();
			}
			catch (Exception)
			{
				throw;
			}
			finally
			{
				if (conn != null)
				{
					conn.Close();
					SqlConnection.ClearPool(conn);
				}
			}
		}
		catch
		{
		}


		try
		{
			BXInstaller.RestoreDb(string.Format(connectionStringFull, txtServer.Text, txtUserLogin.Text, txtUserPass.Text, txtDbName.Text) + "Timeout=1000;");
		}
		catch
		{
			Errors.AddErrorHtml(BXInstaller.GetMessage(this, "Error.UnableToSetupDB"));
			return;
		}

		config.Save();

		base.OnNext(sender, arg);
	}
}
