using System;
using System.Collections.Generic;
using System.Web;

using Bitrix.Components;
using Bitrix.Security;
using Bitrix.UI;
using Bitrix.DataTypes;
using Bitrix;
using Bitrix.Services;


public partial class LoginComponent : BXComponent
{
	public string ProfilePath
	{
		get { return BXUri.ToRelativeUri(Parameters.Get<string>("ProfilePath", string.Empty)); }
	}

    private string ReplaceParameters(string src, IDictionary<string, string> paramDic)
    {
        if (string.IsNullOrEmpty(src))
            return string.Empty;

        int paramCount = paramDic != null ? paramDic.Keys.Count : 0;
        if (paramDic == null || paramDic.Keys.Count == 0)
            return src;

        string result = src;

        foreach (string key in paramDic.Keys)
        {
            if (string.IsNullOrEmpty(key))
                continue;

            string paramVal = paramDic[key];
            if (paramVal == null)
                paramVal = string.Empty;
            int index = -1;
            while ((index = result.IndexOf(key, 0, StringComparison.InvariantCultureIgnoreCase)) >= 0)
                result = string.Concat(result.Substring(0, index), paramVal, result.Substring(index + key.Length));
        }
        return result;
    }

    public string LoginRedirectPath
	{
		get
		{
            string result = Parameters.Get<string>("LoginRedirectPath", string.Empty);
            return !string.IsNullOrEmpty(result) ? BXUri.ToRelativeUri(result) : string.Empty; 
		}
	}

	public string PasswordRecoveryPath
	{
		get { return BXUri.ToRelativeUri(Parameters.Get<string>("PasswordRecoveryPath", string.Empty)); }
	}

	public string PasswordRecoveryCodePath
	{
		get { return BXUri.ToRelativeUri(Parameters.Get<string>("PasswordRecoveryCodePath", string.Empty)); }
	}

	public string RegisterPath
	{
		get 
        {
            string r = Parameters.Get<string>("RegisterPath", string.Empty);
            if (!string.IsNullOrEmpty(r))
            {
                Dictionary<string, string> paramDic = new Dictionary<string, string>();
                paramDic.Add("#ReturnUrl#", HttpUtility.UrlEncode(GetReturnUrl()));
                r = ReplaceParameters(r, paramDic);
                r = BXUri.ToRelativeUri(r);
            }
            return r;
        }
	}

	public bool RequiresQuestionAndAnswer
	{
		get { return BXUserManager.Provider.RequiresQuestionAndAnswer; }
	}

	public bool RequiresCheckWord
	{
		get { return BXUserManager.Provider.RequiresCheckWord; }
	}

	public bool EnablePasswordReset
	{
		get { return BXUserManager.Provider.EnablePasswordReset; }
	}

	protected void Page_Load(object sender, EventArgs e)
    {
        Results["CacheMode"] = "None";
        Parameters["CacheMode"] = "None";

        IncludeComponentTemplate();
    }

    protected override void PreLoadComponentDefinition()
	{
		Title = GetMessage("Title");
        Description = GetMessage("Description");
        Icon = "images/user_authform.gif";

		Group = new BXComponentGroup("Auth", GetMessage("Group"), 100, BXComponentGroup.Utility);

        ParamsDefinition.Add(
            "PasswordRecoveryPath",
            new BXParamText(
                GetMessageRaw("PathToPasswordRecoveryScript"),
                String.Empty,
                BXCategory.Main
                )
            );

        ParamsDefinition.Add(
            "PasswordRecoveryCodePath",
            new BXParamText(
                GetMessageRaw("PathToControlWordScript"),
                String.Empty,
                BXCategory.Main
                )
            );

        ParamsDefinition.Add(
            "LoginRedirectPath",
            new BXParamText(
                GetMessageRaw("PathToSuccessfulLoginRedirectionScript"),
                String.Empty,
                BXCategory.Main
                )
            );

        ParamsDefinition.Add(
            "ProfilePath",
            new BXParamText(
                GetMessageRaw("PathToUserProfile"),
                String.Empty,
                BXCategory.Main
                )
            );

        ParamsDefinition.Add(
            "RegisterPath",
            new BXParamText(
                GetMessageRaw("PathToUserRegistrationScript"),
                String.Empty,
                BXCategory.Main
                )
            );
    }

    private string GetReturnUrl()
    {
        HttpContext current = HttpContext.Current;
        string str = current.Request.QueryString["ReturnUrl"];
        if (str == null)
        {
            str = current.Request.Form["ReturnUrl"];
            if ((!string.IsNullOrEmpty(str) && !str.Contains("/")) && str.Contains("%"))
            {
                str = HttpUtility.UrlDecode(str);
            }
        }
        if (str == null)
        {
			if (!String.IsNullOrEmpty(this.LoginRedirectPath))
				return this.LoginRedirectPath;
            else
                return current.Request.RawUrl;
        }
        return str;
    }

    public override bool ProcessCommand(string commandName, BXParamsBag<object> commandParameters,
                                        List<string> commandErrors)
    {
        if (commandName.Equals("login", StringComparison.InvariantCultureIgnoreCase))
        {
            string providerName = null;

            string login = (string)commandParameters["Login"];
            string val1 = (string)commandParameters["Password"];
            bool remember = (bool)commandParameters["Remember"];

            try
            {
                if (BXAuthentication.Authenticate(login, val1, out providerName))
                {
                    BXAuthentication.SetAuthCookie(login, providerName, remember);
                    Response.Redirect(GetReturnUrl(), true);
                }
                else
                {
                    commandErrors.Add(GetMessage("Error.InvalidLoginOrPassword"));
                }
            }
            catch (Exception e)
            {
                commandErrors.Add(e.Message);
            }
        }
        if (commandName.Equals("logout", StringComparison.InvariantCultureIgnoreCase))
        {
            BXAuthentication.SignOut();
            #region old
            //Response.Clear();
            //Response.StatusCode = 200;
            //if ((Page.Form == null) || !string.Equals(Page.Form.Method, "get", StringComparison.OrdinalIgnoreCase))
            //    Response.Redirect(Request.RawUrl, true );
            //else
            //    Response.Redirect(Request.Path, true);
            #endregion
            //перегрузка страницы, инициирует window.location.href = "http://website/default.aspx"; Абсолютный URL гарантирует новый запрос страницы.
            BXPage page = Page as BXPage;
            if (page != null)
                page.Redirect(BXSefUrlManager.CurrentUrl.ToString());
            else
            {
				try { Response.Redirect(BXSefUrlManager.CurrentUrl.ToString(), true); }
                catch (System.Threading.ThreadAbortException /*exp*/ ) { }
            }
        }
        return false;
    }
}
