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.Text;
using Bitrix;
using Bitrix.DataLayer;
using Bitrix.Modules;
using System.Collections.Generic;
using Bitrix.Security;
using Bitrix.Configuration;
using Bitrix.Blog;

public enum BlogEditorMode
{
    Creation = 1,
    Modification = 2
}

public enum BlogEditorError
{
    None                = 0,
    BlogIsNotFound      = -1,
    BlogOwnerIsNotFound = -2,
    BlogCreation        = -3,
    BlogModification    = -4,
    BlogDeleting        = -5
}

public partial class bitrix_admin_BlogEdit : BXAdminPage
{
	private int? _blogId = null;
	protected int BlogId
	{
        get 
        {
            if (_blogId.HasValue)
                return _blogId.Value;

            string blogIdStr = Request.QueryString["id"];
            if (string.IsNullOrEmpty(blogIdStr))
                 _blogId = 0;
            else
            {
                try
                {
                    _blogId = Convert.ToInt32(Request.QueryString["id"]);
                }
                catch (Exception /*exc*/)
                {
                    _blogId = 0;
                }
            }
            return _blogId.Value; 
        }
	}

    private BlogEditorMode _editorMode = BlogEditorMode.Creation;
    protected BlogEditorMode EditorMode
    {
        get { return _editorMode; }
    }

    private BXBlog _blog;
    protected BXBlog Blog
    {
        get { return _blog; }
    }

    private string _errorMessage = string.Empty;
    protected string ErrorMessage
    {
        get { return _errorMessage; }
    }

    private BlogEditorError _editorError = BlogEditorError.None;
    protected BlogEditorError EditorError
    {
        get { return _editorError; }
    }

	protected override string BackUrl
	{
		get { return !string.IsNullOrEmpty(base.BackUrl) ? base.BackUrl : "BlogList.aspx"; }
	}

	protected void Page_Init(object sender, EventArgs e)
	{
		if (!BXPrincipal.Current.IsCanOperate(BXBlog.Operations.AdminManagement))
			BXAuthentication.AuthenticationRequired();

		BXBlogCategoryCollection categoryList = BXBlogCategory.GetList(
			null,
			null,
			new BXSelect(
				BXSelectFieldPreparationMode.Normal,
				BXBlogCategory.Fields.Id,
				BXBlogCategory.Fields.Name
				),
			null,
			BXTextEncoder.EmptyTextEncoder
			);

		ListItemCollection categoryItems = BlogCategories.Items;
		categoryItems.Clear();

		foreach (BXBlogCategory category in categoryList)
			categoryItems.Add(new ListItem(category.Name, category.Id.ToString()));

		#region OLD
		/*
        BXUserCollection users = Bitrix.Security.BXUser.GetList(
            null,
            new BXOrderBy(
                new BXOrderByPair(Bitrix.Security.BXUser.Fields.UserName, BXOrderByDirection.Asc)
                ),
            new BXSelect(
                Bitrix.Security.BXUser.Fields.UserId,
                Bitrix.Security.BXUser.Fields.UserName,
                Bitrix.Security.BXUser.Fields.FirstName,
                Bitrix.Security.BXUser.Fields.LastName,
                Bitrix.Security.BXUser.Fields.ProviderName
                ),
                null
            );

        ListItemCollection userItems = BlogOwner.Items;
        foreach (Bitrix.Security.BXUser user in users)
        {
            userItems.Add(new ListItem(string.Format("[{0}] {1} {2}", user.UserName, user.FirstName, user.LastName), user.UserId.ToString()));
        }
        */
		#endregion

		#region DEFFERED
		/*
        BlogPostVisibilityMode.Items.Add(new ListItem("(не выбрано)", "_None"));
        BlogPostVisibilityMode.Items.Add(new ListItem(BXBlogEnumHelper.GetPostVisibilityModeName(BXBlogPostVisibilityMode.Everyone), BXBlogPostVisibilityMode.Everyone.ToString("G")));
        BlogPostVisibilityMode.Items.Add(new ListItem(BXBlogEnumHelper.GetPostVisibilityModeName(BXBlogPostVisibilityMode.Registered), BXBlogPostVisibilityMode.Registered.ToString("G")));
        //BlogPostVisibilityMode.Items.Add(new ListItem(BXBlogEnumHelper.GetPostVisibilityModeName(BXBlogPostVisibilityMode.Friends), BXBlogPostVisibilityMode.Friends.ToString("G")));
        BlogPostVisibilityMode.Items.Add(new ListItem(BXBlogEnumHelper.GetPostVisibilityModeName(BXBlogPostVisibilityMode.Author), BXBlogPostVisibilityMode.Author.ToString("G")));

        BlogAddCommentPermission.Items.Add(new ListItem("(не выбрано)", "_None"));
        BlogAddCommentPermission.Items.Add(new ListItem(BXBlogEnumHelper.GetAddCommentPermissionName(BXBlogAddCommentPermission.Everyone), BXBlogAddCommentPermission.Everyone.ToString("G")));
        BlogAddCommentPermission.Items.Add(new ListItem(BXBlogEnumHelper.GetAddCommentPermissionName(BXBlogAddCommentPermission.Registered), BXBlogAddCommentPermission.Registered.ToString("G")));
        //BlogAddCommentPermission.Items.Add(new ListItem(BXBlogEnumHelper.GetAddCommentPermissionName(BXBlogAddCommentPermission.Friends), BXBlogAddCommentPermission.Friends.ToString("G")));
        BlogAddCommentPermission.Items.Add(new ListItem(BXBlogEnumHelper.GetAddCommentPermissionName(BXBlogAddCommentPermission.NoOne), BXBlogAddCommentPermission.NoOne.ToString("G")));

        BlogCommentApproval.Items.Add(new ListItem("(не выбрано)", "_None"));
        BlogCommentApproval.Items.Add(new ListItem(BXBlogEnumHelper.GetCommentApprovalName(BXBlogCommentApproval.None), BXBlogCommentApproval.None.ToString("G")));
        BlogCommentApproval.Items.Add(new ListItem(BXBlogEnumHelper.GetCommentApprovalName(BXBlogCommentApproval.Anonymous), BXBlogCommentApproval.Anonymous.ToString("G")));
        BlogCommentApproval.Items.Add(new ListItem(BXBlogEnumHelper.GetCommentApprovalName(BXBlogCommentApproval.NotFriends), BXBlogCommentApproval.NotFriends.ToString("G")));
        BlogCommentApproval.Items.Add(new ListItem(BXBlogEnumHelper.GetCommentApprovalName(BXBlogCommentApproval.Everything), BXBlogCommentApproval.Everything.ToString("G")));
        */
		#endregion
		
		if (IsPostBack)
			Validate();

		TryLoadBlog();
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		BXBlog blog = Blog;
		string title = EditorMode == BlogEditorMode.Modification ? string.Format(GetMessage("PageTitle.EditBlog"), blog != null ? HttpUtility.HtmlEncode(blog.Name) : "?") : GetMessage("PageTitle.CreateBlog");

		MasterTitle = title;
		Page.Title = title;

	}

	private void TryLoadBlog()
	{
        int id = BlogId;
        if (id <= 0)
        {
            _editorMode = BlogEditorMode.Creation;
            _blog = new BXBlog();
        }
        else
        {
            _editorMode = BlogEditorMode.Modification;
            if ((_blog = BXBlog.GetById(id, BXTextEncoder.EmptyTextEncoder)) == null)
            {
                _errorMessage = string.Format(GetMessageRaw("Error.UnableToFindBlog"), id);
                _editorError = BlogEditorError.BlogIsNotFound;
                return;
            }
        }

		if (_editorMode == BlogEditorMode.Modification)
        {
            BlogActive.Checked = _blog.Active;
            BlogName.Text = _blog.Name;
            BlogSlug.Text = _blog.Slug;
            BlogDescription.Text = _blog.Description;
            BlogSort.Text = _blog.Sort.ToString();
            BlogNotifyOfComments.Checked = _blog.NotifyOfComments;
            BlogXmlId.Text = _blog.XmlId;
            ListItemCollection categoryItems = BlogCategories.Items;
            int[] categoryIds = _blog.GetCategoryIds();
            foreach (int categoryId in categoryIds)
            {
                ListItem li = categoryItems.FindByValue(categoryId.ToString());
                if (li != null)
                    li.Selected = true;
            }

            #region OLD
            /*
            if (!_blog.IsNew)
            {
                ListItemCollection userItems = BlogOwner.Items;
                ListItem userItem = userItems.FindByValue(_blog.OwnerId.ToString());
                if (userItem != null)
                    userItem.Selected = true;
            }
            */
            #endregion

            BlogOwner.Text = !_blog.IsNew ? _blog.Owner.GetUserName() : (BXUser.Identity as BXIdentity).Name;

            #region DEFFERED
            /*
            ListItem postVisibilityModeItem = BlogPostVisibilityMode.Items.FindByValue(_blog.PostVisibilityMode.ToString("G"));
            if (postVisibilityModeItem != null)
                postVisibilityModeItem.Selected = true;

            ListItem addCommentPermissionItem = BlogAddCommentPermission.Items.FindByValue(_blog.AddCommentPermission.ToString("G"));
            if (addCommentPermissionItem != null)
                addCommentPermissionItem.Selected = true;

            ListItem commentApprovalItem = BlogCommentApproval.Items.FindByValue(_blog.CommentApproval.ToString("G"));
            if (commentApprovalItem != null)
                commentApprovalItem.Selected = true;
            */
            #endregion
        }
        else
        {
			BlogActive.Checked = true;
			BlogSort.Text = "10";
			BlogNotifyOfComments.Checked = true;
        }
	}

    private void TrySaveBlog()
    {
        if (_blog == null)
            return;
        try
        {
			string userName = BlogOwner.Text;
			if (!string.IsNullOrEmpty(userName))
			{
				BXUserCollection users = Bitrix.Security.BXUser.GetList(
					new BXFilter(new BXFilterItem(Bitrix.Security.BXUser.Fields.UserName, BXSqlFilterOperators.Equal, userName)),
					null,
					null,
					null
					);
				if (users.Count > 0)
					_blog.OwnerId = users[0].UserId;
				else
				{
					_errorMessage = string.Format(GetMessageRaw("Error.UnableToFindUser"), userName);
					_editorError = BlogEditorError.BlogOwnerIsNotFound;
				}
			}
			else
				_blog.OwnerId = 0;

			_blog.Active = BlogActive.Checked;
			_blog.Name = BlogName.Text;
			_blog.Slug = BlogSlug.Text;
			_blog.Description = BlogDescription.Text;
			if (string.IsNullOrEmpty(BlogSort.Text))
				_blog.Sort = 0;
			else
			{
				try
				{
					_blog.Sort = Convert.ToInt32(BlogSort.Text);
				}
				catch (Exception /*exc*/) { }
			}

			_blog.NotifyOfComments = BlogNotifyOfComments.Checked;
			_blog.XmlId = BlogXmlId.Text;

			List<int> categoryIdList = new List<int>();
			ListItemCollection categoryItems = BlogCategories.Items;
			foreach (ListItem categoryItem in categoryItems)
			{
				if (!categoryItem.Selected)
					continue;
				try
				{
					categoryIdList.Add(Convert.ToInt32(categoryItem.Value));
				}
				catch (Exception /*exc*/)
				{
				}
			}
			_blog.SetCategoryIds(categoryIdList.ToArray());
			#region DEFFERED
			/*
            string postVisibilityModeStr = BlogPostVisibilityMode.SelectedValue;
            if (string.IsNullOrEmpty(postVisibilityModeStr) || string.Equals(postVisibilityModeStr, "_None", StringComparison.InvariantCultureIgnoreCase))
                _blog.PostVisibilityMode = BXBlogPostVisibilityMode.Everyone;
            else
            {
                try
                {
                    _blog.PostVisibilityMode = (BXBlogPostVisibilityMode)Enum.Parse(typeof(BXBlogPostVisibilityMode), postVisibilityModeStr);
                }
                catch (Exception exc)
                {
                    _blog.PostVisibilityMode = BXBlogPostVisibilityMode.Everyone;
                }
            }

            string addCommentPermissionStr = BlogAddCommentPermission.SelectedValue;
            if (string.IsNullOrEmpty(addCommentPermissionStr) || string.Equals(addCommentPermissionStr, "_None", StringComparison.InvariantCultureIgnoreCase))
                _blog.AddCommentPermission = BXBlogAddCommentPermission.Everyone;
            else
            {
                try
                {
                    _blog.AddCommentPermission = (BXBlogAddCommentPermission)Enum.Parse(typeof(BXBlogAddCommentPermission), addCommentPermissionStr);
                }
                catch (Exception exc)
                {
                    _blog.AddCommentPermission = BXBlogAddCommentPermission.Everyone;
                }
            }

            string commentApprovalStr = BlogCommentApproval.SelectedValue;
            if (string.IsNullOrEmpty(commentApprovalStr) || string.Equals(commentApprovalStr, "_None", StringComparison.InvariantCultureIgnoreCase))
                _blog.CommentApproval = BXBlogCommentApproval.None;
            else
            {
                try
                {
                    _blog.CommentApproval = (BXBlogCommentApproval)Enum.Parse(typeof(BXBlogCommentApproval), commentApprovalStr);
                }
                catch (Exception exc)
                {
                    _blog.CommentApproval = BXBlogCommentApproval.None;
                }
            }
            */
			#endregion

            _blog.Save();
			_blogId = _blog.Id;
        }
        catch (Exception exc)
        {
            _errorMessage = exc.Message;
            _editorError = EditorMode == BlogEditorMode.Creation ? BlogEditorError.BlogCreation : BlogEditorError.BlogModification; 
        }
    }

    protected override void OnPreRender(EventArgs e)
    {
        if (EditorError != BlogEditorError.None)
        {
            errorMessage.AddErrorMessage(ErrorMessage);
            if (EditorMode == BlogEditorMode.Modification)
            {
                if (EditorError == BlogEditorError.BlogIsNotFound)
                    TabControl.Visible = false;
            }
        }

        if (EditorMode != BlogEditorMode.Modification)
        {
            AddButton.Visible = false;
            DeleteButton.Visible = false;
        }

        /*
        BXBlogUserCollection users = BXBlogUser.GetList(
            null,
            new BXOrderBy(
                new BXOrderByPair(BXBlogUser.Fields.User.UserName, BXOrderByDirection.Asc)
                ),
            new BXSelect(
                BXBlogUser.Fields.User.UserId,
                BXBlogUser.Fields.User.UserName,
                BXBlogUser.Fields.User.FirstName,
                BXBlogUser.Fields.User.LastName,
                BXBlogUser.Fields.User.ProviderName
                ),
                null
            );


        ListItemCollection userItems = BlogOwner.Items;
        foreach (BXBlogUser user in users)
        {
            Bitrix.Security.BXUser sysUser = user.User;
            if (sysUser == null)
                continue;
            userItems.Add(new ListItem(string.Format("[{0}] {1} {2}", sysUser.UserName, sysUser.FirstName, sysUser.LastName), sysUser.UserId.ToString()));
        }
        */
        base.OnPreRender(e);
    }


	protected void OnBlogEdit(object sender, BXTabControlCommandEventArgs e)
	{
		switch (e.CommandName)
		{
            case "save":
                {
                    if (IsValid && EditorError == BlogEditorError.None)
                    {
                        TrySaveBlog();
                        if (EditorError == BlogEditorError.None)
                            GoBack(); 
                    }
                }
                break;
            case "apply":
                {
                    if (IsValid && EditorError == BlogEditorError.None)
                    {
                        TrySaveBlog();
                        if (EditorError == BlogEditorError.None)
                            Response.Redirect(string.Format("BlogEdit.aspx?id={0}&tabindex={1}", BlogId.ToString(), TabControl.SelectedIndex));
                    }
                }
                break;
			case "cancel":
				GoBack();
				break;
		}
	}

	protected void OnToolBarButtonClick(object sender, CommandEventArgs e)
	{
        if (!IsValid)
            return;

		if (e.CommandName == "delete")
		{
			try
			{
                BXBlog blog = Blog;
                if (blog != null)
                    blog.Delete();

				GoBack();
			}
			catch (Exception ex)
			{
                _errorMessage = ex.Message;
                _editorError = BlogEditorError.BlogDeleting;
			}
		}
	}
}
