using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using Bitrix.Components;
using Bitrix.DataTypes;
using Bitrix.IO;
using Bitrix.Services.Text;
using Bitrix.UI;
using Bitrix.Security;
using Bitrix.DataLayer;

namespace Bitrix.Blog.Components
{
    public partial class BlogMenuComponent : BXComponent
    {
		private ErrorCode fatalError = ErrorCode.FatalComponentNotExecuted;

		public ErrorCode FatalError
		{
			get
			{
				return fatalError;
			}
		}
		public string BlogIndexUrl
		{
			get
			{
				return Parameters.GetString("BlogIndexUrl");
			}
			set
			{
				Parameters["BlogIndexUrl"] = value;
			}
		}
		public string UserProfileUrlTemplate
		{
			get
			{
				return Parameters.GetString("UserProfileUrlTemplate");
			}
			set
			{
				Parameters["UserProfileUrlTemplate"] = value;
			}
		}
		public string NewPostUrlTemplate
		{
			get
			{
				return Parameters.GetString("NewPostUrlTemplate");
			}
			set
			{
				Parameters["NewPostUrlTemplate"] = value;
			}
		}
		public string UserBlogUrlTemplate
		{
			get
			{
				return Parameters.GetString("UserBlogUrlTemplate");
			}
			set
			{
				Parameters["UserBlogUrlTemplate"] = value;
			}
		}
		public string UserBlogSettingsUrlTemplate
		{
			get
			{
				return Parameters.GetString("UserBlogSettingsUrlTemplate");
			}
			set
			{
				Parameters["UserBlogSettingsUrlTemplate"] = value;
			}
		}
		public string DraftPostListUrlTemplate
		{
			get
			{
				return Parameters.GetString("DraftPostListUrlTemplate");
			}
			set
			{
				Parameters["DraftPostListUrlTemplate"] = value;
			}
		}
        private List<MenuItem> menuItems;
		public List<MenuItem> MenuItems
		{
			get
			{
				return menuItems;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			fatalError = ErrorCode.None;

			int userId = BXIdentity.Current.Id;

			if (userId < 1)
			{
				fatalError = ErrorCode.Unauthorized;
				return;
			}

			BXBlogCollection blogCollection = BXBlog.GetList(
				new BXFilter(
					new BXFilterItem(BXBlog.Fields.Active, BXSqlFilterOperators.Equal, true),
					new BXFilterItem(BXBlog.Fields.Owner.Id, BXSqlFilterOperators.Equal, userId),
					new BXFilterItem(BXBlog.Fields.Categories.Category.Sites.Site.ID, BXSqlFilterOperators.Equal, DesignerSite)
				),
				null
			);

			if (blogCollection.Count < 1)
			{
				fatalError = ErrorCode.BlogNotFound;
				return;
			}

			BXBlog blog = blogCollection[0];
			BXParamsBag<object> replace = new BXParamsBag<object>();
			replace.Add("UserId", userId);
			replace.Add("BlogSlug", blog.Slug);
			replace.Add("BlogId", blog.Id);

			menuItems = new List<MenuItem>();

			if (!String.IsNullOrEmpty(NewPostUrlTemplate))
				menuItems.Add(new MenuItem(GetMessageRaw("UrlTitle.NewPost"), ResolveTemplateUrl(NewPostUrlTemplate, replace), "newpost", ""));

			if (!String.IsNullOrEmpty(DraftPostListUrlTemplate))
				menuItems.Add(new MenuItem(GetMessageRaw("UrlTitle.Draft"), ResolveTemplateUrl(DraftPostListUrlTemplate, replace), "draft", ""));

			if (!String.IsNullOrEmpty(UserBlogUrlTemplate))
				menuItems.Add(new MenuItem(GetMessageRaw("UrlTitle.UserBlog"), ResolveTemplateUrl(UserBlogUrlTemplate, replace), "user-blog", ""));

			if (!String.IsNullOrEmpty(UserProfileUrlTemplate))
				menuItems.Add(new MenuItem(GetMessageRaw("UrlTitle.Profile"), ResolveTemplateUrl(UserProfileUrlTemplate, replace), "profile", ""));

			if (!String.IsNullOrEmpty(UserBlogSettingsUrlTemplate))
				menuItems.Add(new MenuItem(GetMessageRaw("UrlTitle.UserBlogSettings"), ResolveTemplateUrl(UserBlogSettingsUrlTemplate, replace), "blog-settings", ""));

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

			foreach (string param in new string[] { Parameters.GetString("ThemeCssFilePath"), Parameters.GetString("ColorCssFilePath") })
			{
				if (BXStringUtility.IsNullOrTrimEmpty(param))
					continue;

				string path = param;
				try
				{
					path = BXPath.ToVirtualRelativePath(path);
					if (BXSecureIO.FileExists(path))
						BXPage.RegisterStyle(path);
				}
				catch {}
			}
		}
        protected override void PreLoadComponentDefinition()
        {
            Title = GetMessageRaw("Title");
            Description = GetMessageRaw("Description");
            Icon = "images/icon.gif";
            Group = BXBlogModuleConfiguration.GetComponentGroup();

			BXCategory urlCategory = BXCategory.UrlSettings;
            BXCategory mainCategory = BXCategory.Main;

			ParamsDefinition.Add("ThemeCssFilePath", new BXParamText(GetMessageRaw("Param.ThemeCssFilePath"), "~/bitrix/components/bitrix/blog/templates/.default/style.css", mainCategory));
			ParamsDefinition.Add("ColorCssFilePath", new BXParamText(GetMessageRaw("Param.ColorCssFilePath"), "~/bitrix/components/bitrix/blog/templates/.default/themes/default/style.css", mainCategory));

			ParamsDefinition.Add("NewPostUrlTemplate", new BXParamText(GetMessageRaw("Param.NewPostUrlTemplate"), "", urlCategory));
			ParamsDefinition.Add("DraftPostListUrlTemplate", new BXParamText(GetMessageRaw("Param.DraftPostListUrlTemplate"), "", urlCategory));
			ParamsDefinition.Add("UserBlogUrlTemplate", new BXParamText(GetMessageRaw("Param.UserBlogUrlTemplate"), "", urlCategory));
			ParamsDefinition.Add("UserBlogSettingsUrlTemplate", new BXParamText(GetMessageRaw("Param.UserBlogSettingsUrlTemplate"), "", urlCategory));
			ParamsDefinition.Add("BlogIndexUrl", new BXParamText(GetMessageRaw("Param.BlogIndexUrl"), "", urlCategory));
			ParamsDefinition.Add("UserProfileUrlTemplate", new BXParamText(GetMessageRaw("Param.UserProfileUrlTemplate"), "", urlCategory));
        }

		public class MenuItem
		{
			private string href;
			private string titleHtml;
			private string className;
			private string tooltipHtml;

			public string TooltipHtml
			{
				get
				{
					return tooltipHtml;
				}
				internal set
				{
					tooltipHtml = value;
				}
			}
			public string ClassName
			{
				get
				{
					return className;
				}
				internal set
				{
					className = value;
				}
			}
            public string TitleHtml
			{
				get
				{
					return titleHtml;
				}
				internal set
				{
					titleHtml = value;
				}
			}
			public string Href
			{
				get
				{
					return href;
				}
				internal set
				{
					href = value;
				}
			}

			internal MenuItem(string title, string url, string cssClass, string tooltip)
			{
				titleHtml = title != null ? HttpUtility.HtmlEncode(title) : null;
				href = url != null ? HttpUtility.HtmlEncode(url) : null;
				className = cssClass != null ? HttpUtility.HtmlEncode(cssClass) : null;
				tooltipHtml = tooltip != null ? HttpUtility.HtmlEncode(tooltip) : null;
			}
		}

		public enum ErrorCode
		{
			None = 0,
			Unauthorized = 1,
			BlogNotFound = 2,
			FatalComponentNotExecuted = 4
		}
    }

	public class BlogMenuTemplate : BXComponentTemplate<BlogMenuComponent>
    {
        protected override void Render(HtmlTextWriter writer)
        {
            StartWidth = "100%";
            if (IsComponentDesignMode)
            {
               
            }
            base.Render(writer);
        }
    }
}
