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.Components;
using System.Collections.Generic;
using Bitrix.UI;
using Bitrix.DataTypes;
using System.Threading;


public partial class bitrix_components_bitrix_system_register_templates__default_template : BXComponentTemplate<RegisterComponent>
{
    private class CaptchaValidator: BaseValidator
    {

        private BXCaptchaEngine _captchaEng = null;
        private TextBox _responseTbx = null;
        private HiddenField _guidHf = null;
        BXValidationSummary _summary = null;
        private string _errorMessage = string.Empty;

        public CaptchaValidator(HiddenField guidHf, TextBox responseTbx, BXValidationSummary summary) 
        {
            if (guidHf == null)
                throw new ArgumentNullException("guidHf");
            if (responseTbx == null)
                throw new ArgumentNullException("responseTbx");

            _guidHf = guidHf;
            _responseTbx = responseTbx;
            _summary = summary;

            ControlToValidate = _responseTbx.ID;
        }

        public BXCaptchaEngine CaptchaEngine
        {
            get 
            {
                if (_captchaEng != null)
                    return _captchaEng;

                if (!Page.IsPostBack)
                    _captchaEng = BXCaptchaEngine.Create(BXCaptchaEngineStorage.HttpRuntime);
                else
                {
                    string guid = Page.Request.Form[_guidHf.UniqueID];
                    _captchaEng = BXCaptchaEngine.Get(BXCaptchaEngineStorage.HttpRuntime, guid);
                }

                _captchaEng.MaxTimeout = 1800;
                _guidHf.Value = _captchaEng.Id;

                return _captchaEng; 
            }
        }

        public string GetCaptchaImageUrl()
        {
           return _captchaEng.Store();
        }

        public string CaptchaValidationErrorMessage
        {
            get { return _errorMessage; }
        }

        #region BaseValidator
        protected override bool EvaluateIsValid()
        {
            _errorMessage = CaptchaEngine.Validate(_responseTbx.Text);
            bool result = string.IsNullOrEmpty(_errorMessage);
            if (!result && _summary != null)
                _summary.AddErrorText(_errorMessage);
            return result;
        }
        #endregion
    }

    CaptchaValidator _captchaValidator = null;
    private bool _isValid = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        _captchaValidator = new CaptchaValidator(hfCaptchaGuid, tbxCaptcha, errorMessage);
        Controls.Add(_captchaValidator);
        _captchaValidator.ValidationGroup = "CreateUserWizard1";

        //CreateUserStep1.Visible = true;
        //CreateUserStep2.Visible = false;

        trQuestion.Visible = Component.RequiresQuestionAndAnswer;
        trAnswer.Visible = Component.RequiresQuestionAndAnswer;
		rfvDisplayName.Enabled = (Component.DisplayNameFieldMode == RegisterComponent.FieldMode.Require);
		rfvFirstName.Enabled = (Component.FirstNameFieldMode == RegisterComponent.FieldMode.Require);
		rfvLastName.Enabled = (Component.LastNameFieldMode == RegisterComponent.FieldMode.Require);
	}

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (!Page.IsPostBack || !_isValid)
        {
            BXCaptchaEngine captchaEng = _captchaValidator.CaptchaEngine;
            tbxCaptcha.MaxLength = captchaEng.Captcha.Length;
            tbxCaptcha.Attributes.Add("length", (2 * captchaEng.Captcha.Length).ToString());
            imgCaptcha.ImageUrl = _captchaValidator.GetCaptchaImageUrl();
        }
    }

	//protected string _registredDisplayName = string.Empty;
	//protected string _registredFirstName = string.Empty;
	//protected string _registredLastName = string.Empty;
	//protected string _registredLogin = string.Empty;
	//protected string _registredEmail = string.Empty;

	protected void Button1_Click(object sender, EventArgs e)
	{
        _isValid = Page.IsValid;
        if (_isValid)
        {
			//_registredFirstName = tbFirstName.Text;
			//_registredLastName = tbLastName.Text;
			//_registredLogin = tbLogin.Text;
			//_registredEmail = tbEmail.Text;

            BXParamsBag<object> par = new BXParamsBag<object>();
			par.Add("DisplayName", Component.DisplayNameFieldMode != RegisterComponent.FieldMode.Hide ? tbDisplayName.Text : null);
			par.Add("FirstName", Component.FirstNameFieldMode != RegisterComponent.FieldMode.Hide ? tbFirstName.Text : null);
			par.Add("LastName", Component.LastNameFieldMode != RegisterComponent.FieldMode.Hide ? tbLastName.Text : null);
			par.Add("Login", tbLogin.Text);
            par.Add("Password", tbPassword.Text);
			par.Add("Email", tbEmail.Text);
            par.Add("Question", tbQuestion.Text);
            par.Add("Answer", tbAnswer.Text);

            List<string> err = new List<string>();

            if (!Component.ProcessCommand("register", par, err))
            {
                foreach (string kvp in err)
                    errorMessage.AddErrorMessage(kvp);
                _isValid = false;
            }
            else
            {
                //CreateUserStep1.Visible = false;
                //CreateUserStep2.Visible = true;
                string redirectUrl = Component.GetRedirectUrl();
                if (string.IsNullOrEmpty(redirectUrl))
                    redirectUrl = "~/";
                try
                {
                    Response.Redirect(redirectUrl);
                }
                catch (ThreadAbortException /*exc*/) { }
            }
        }
	}

    protected override void PrepareDesignMode()
    {
        MinimalWidth = "530";
        MinimalHeight = "410";
        //StartWidth = "530";
        //StartHeight = "410";
    }
}
