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

using Bitrix.Components;
using Bitrix.Components.Editor;
using Bitrix.DataLayer;
using Bitrix.DataTypes;
using Bitrix.IO;
using Bitrix.Modules;
using Bitrix.Services;
using Bitrix.Services.Text;
using Bitrix.UI;

namespace Bitrix.Blog.Components
{
	public partial class BlogComponent : BXComponent
	{
		//PROPERTIES
		private string BlogVariable
		{
			get
			{
				return Parameters.GetString("BlogVariable", "blog");
			}
			set
			{
				Parameters["BlogVariable"] = value;
			}
		}
		private string CategoryVariable
		{
			get
			{
				return Parameters.GetString("CategoryVariable", "category");
			}
			set
			{
				Parameters["CategoryVariable"] = value;
			}
		}
		private string CommentVariable
		{
			get
			{
				return Parameters.GetString("CommentVariable", "");
			}
			set
			{
				Parameters["CommentVariable"] = value;
			}
		}
		private string PostVariable
		{
			get
			{
				return Parameters.GetString("PostVariable", "");
			}
			set
			{
				Parameters["PostVariable"] = value;
			}
		}
		private string ActionVariable
		{
			get
			{
				return Parameters.GetString("ActionVariable", "");
			}
			set
			{
				Parameters["ActionVariable"] = value;
			}
		}
		private string PageVariable
		{
			get
			{
				return Parameters.GetString("PageVariable", "");
			}
			set
			{
				Parameters["PageVariable"] = value;
			}
		}
		private string UserVariable
		{
			get
			{
				return Parameters.GetString("UserVariable", "");
			}
			set
			{
				Parameters["UserVariable"] = value;
			}
		}

		public bool ShouldSetPageTitle
		{
			get
			{
				return Parameters.GetBool("SetPageTitle");
			}
			set
			{
				Parameters["SetPageTitle"] = value.ToString();
			}
		}
		public string PageTitle
		{
			get
			{
				return ComponentCache.GetString("PageTitle");
			}
		}

		//METHODS
		public void SetPageTitle(string titleText)
		{
			if (titleText == null)
				return;

			BXPublicPage bitrixPage = Page as BXPublicPage;
			if (bitrixPage != null && !IsComponentDesignMode)
				bitrixPage.BXTitle = Encode(titleText);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			Parameters["PagingBoundedBorderSize"] = "1";

			ComponentCache["PostsPerPage"] = Parameters.GetString("PostsPerPage", "10");
			ComponentCache["BlogsPerPage"] = Parameters.GetString("BlogsPerPage", "20");
			ComponentCache["CommentsPerPage"] = Parameters.GetString("CommentsPerPage", "30");
			ComponentCache["MainPagePostCount"] = Parameters.GetString("MainPagePostCount", "6");
			ComponentCache["MainPageBlogCount"] = Parameters.GetString("MainPageBlogCount", "6");
			
			string page = EnableSef ? PrepareSefMode() : PrepareNormalMode();

            IncludeComponentTemplate(page);
		}
		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;
			BXCategory additionalSettingsCategory = BXCategory.AdditionalSettings;
			BXCategory sefCategory = BXCategory.Sef;

			BXParametersDefinition.SetPaging(ParamsDefinition, ClientID, BXParametersDefinition.PagingParamsOptions.DisableLoad | BXParametersDefinition.PagingParamsOptions.DisableShowAll);
			ParamsDefinition["PagingTemplate"].DefaultValue = "customizable";
			ParamsDefinition["PagingTitle"].DefaultValue = GetMessageRaw("DefaultPagingTitle");
			ParamsDefinition["PagingMaxPages"].DefaultValue = "5";
			ParamsDefinition.Remove("PagingRecordsPerPage");

			ParamsDefinition.Add(BXParametersDefinition.Sef);
			//ParamsDefinition.Add(BXParametersDefinition.Search);

			ParamsDefinition["ColorCss"] = new BXParamSingleSelectionWithText(GetMessageRaw("Param.ColorCss"), "~/bitrix/components/bitrix/blog/templates/.default/themes/default/style.css", mainCategory);

			ParamsDefinition["MaxBlogGroups"] = new BXParamText(GetMessageRaw("Param.MaxBlogGroups"), "1", mainCategory);
			ParamsDefinition["SlugIgnoreList"] = new BXParamText(GetMessageRaw("Param.SlugIgnoreList"), "admin;blog;blogs;users;user;search;posts;rss;tags;new", mainCategory);
			ParamsDefinition["MinSlugLength"] = new BXParamText(GetMessageRaw("Param.MinSlugLength"), "3", mainCategory);
			ParamsDefinition["MaxSlugLength"] = new BXParamText(GetMessageRaw("Param.MaxSlugLength"), "10", mainCategory);

			// Query string variable names
			ParamsDefinition["BlogVariable"] = new BXParamText(GetMessageRaw("Param.BlogVariable"), "blog", sefCategory);
			ParamsDefinition["CategoryVariable"] = new BXParamText(GetMessageRaw("Param.CategoryVariable"), "category", sefCategory);
			ParamsDefinition["CommentVariable"] = new BXParamText(GetMessageRaw("Param.CommentVariable"), "comment", sefCategory);
			ParamsDefinition["PostVariable"] = new BXParamText(GetMessageRaw("Param.PostVariable"), "post", sefCategory);
			ParamsDefinition["ActionVariable"] = new BXParamText(GetMessageRaw("Param.ActionVariable"), "act", sefCategory);
			ParamsDefinition["PageVariable"] = new BXParamText(GetMessageRaw("Param.PageVariable"), "page", sefCategory);
			ParamsDefinition["UserVariable"] = new BXParamText(GetMessageRaw("Param.UserVariable"), "user", sefCategory);

			// Sef templates
			ParamsDefinition["NewPostTemplate"] = new BXParamText(GetMessageRaw("Param.NewPostTemplate"), "/#BlogSlug#/new/", sefCategory);
			ParamsDefinition["PostListTemplate"] = new BXParamText(GetMessageRaw("Param.PostListTemplate"), "/#BlogSlug#/", sefCategory);
			ParamsDefinition["PostListPageTemplate"] = new BXParamText(GetMessageRaw("Param.PostListPageTemplate"), "/#BlogSlug#/?page=#PageId#", sefCategory);
			ParamsDefinition["DraftPostListTemplate"] = new BXParamText(GetMessageRaw("Param.DraftPostListTemplate"), "/#BlogSlug#/draft/", sefCategory);
			ParamsDefinition["DraftPostListPageTemplate"] = new BXParamText(GetMessageRaw("Param.DraftPostListPageTemplate"), "/#BlogSlug#/draft/?page=#PageId#", sefCategory);
			ParamsDefinition["PostTemplate"] = new BXParamText(GetMessageRaw("Param.PostTemplate"), "/#BlogSlug#/#PostId#/", sefCategory);
			ParamsDefinition["PostPageTemplate"] = new BXParamText(GetMessageRaw("Param.PostPageTemplate"), "/#BlogSlug#/#PostId#/?page=#PageId###comments", sefCategory);
			ParamsDefinition["PostEditTemplate"] = new BXParamText(GetMessageRaw("Param.PostEditTemplate"), "/#BlogSlug#/#PostId#/edit/", sefCategory);
			ParamsDefinition["CommentReadTemplate"] = new BXParamText(GetMessageRaw("Param.CommentReadTemplate"), "/#BlogSlug#/#PostId#/#CommentId#/##comment#CommentId#", sefCategory);
			ParamsDefinition["CommentEditTemplate"] = new BXParamText(GetMessageRaw("Param.CommentEditTemplate"), "/#BlogSlug#/#PostId#/#CommentId#/edit/", sefCategory);
			ParamsDefinition["UserProfileTemplate"] = new BXParamText(GetMessageRaw("Param.UserProfileTemplate"), "/users/#UserId#/", sefCategory);
			ParamsDefinition["UserProfileEditTemplate"] = new BXParamText(GetMessageRaw("Param.UserProfileEditTemplate"), "/users/#UserId#/edit/", sefCategory);
			ParamsDefinition["NewBlogTemplate"] = new BXParamText(GetMessageRaw("Param.NewBlogTemplate"), "/new/", sefCategory);
			ParamsDefinition["BlogEditTemplate"] = new BXParamText(GetMessageRaw("Param.BlogEditTemplate"), "/#BlogSlug#/edit/", sefCategory);
			ParamsDefinition["BlogListTemplate"] = new BXParamText(GetMessageRaw("Param.BlogListTemplate"), "/blogs/", sefCategory);
			ParamsDefinition["BlogListPageTemplate"] = new BXParamText(GetMessageRaw("Param.BlogListPageTemplate"), "/blogs/?page=#PageId#", sefCategory);
			ParamsDefinition["CategoryBlogListTemplate"] = new BXParamText(GetMessageRaw("Param.CategoryBlogListTemplate"), "/blogs/#CategoryId#/", sefCategory);
			ParamsDefinition["CategoryBlogListPageTemplate"] = new BXParamText(GetMessageRaw("Param.CategoryBlogListPageTemplate"), "/blogs/#CategoryId#/?page=#PageId#", sefCategory);

			ParamsDefinition["NewPostListTemplate"] = new BXParamText(GetMessageRaw("Param.NewPostListTemplate"), "/posts/", sefCategory);
			ParamsDefinition["NewPostListPageTemplate"] = new BXParamText(GetMessageRaw("Param.NewPostListPageTemplate"), "/posts/?page=#PageId#", sefCategory);
			ParamsDefinition["PopularPostListTemplate"] = new BXParamText(GetMessageRaw("Param.PopularPostListTemplate"), "/posts/popular/", sefCategory);
			ParamsDefinition["PopularPostListPageTemplate"] = new BXParamText(GetMessageRaw("Param.PopularPostListPageTemplate"), "/posts/popular/?page=#PageId#", sefCategory);
			ParamsDefinition["DiscussPostListTemplate"] = new BXParamText(GetMessageRaw("Param.DiscussPostListTemplate"), "/posts/discuss/", sefCategory);
			ParamsDefinition["DiscussPostListPageTemplate"] = new BXParamText(GetMessageRaw("Param.DiscussPostListPageTemplate"), "/posts/discuss/?page=#PageId#", sefCategory);

			//Additional options
			ParamsDefinition["SetPageTitle"] = new BXParamYesNo(GetMessageRaw("Param.SetPageTitle"), true, additionalSettingsCategory);
			ParamsDefinition["MaxWordLength"] = new BXParamText(GetMessageRaw("Param.MaxWordLength"), "15", additionalSettingsCategory);
			ParamsDefinition["PeriodDays"] = new BXParamText(GetMessageRaw("Param.PeriodDays"), "30", additionalSettingsCategory);

			ParamsDefinition["PostsPerPage"] = new BXParamText(GetMessageRaw("Param.PostsPerPage"), "10", additionalSettingsCategory);
			ParamsDefinition["BlogsPerPage"] = new BXParamText(GetMessageRaw("Param.BlogsPerPage"), "20", additionalSettingsCategory);
			ParamsDefinition["CommentsPerPage"] = new BXParamText(GetMessageRaw("Param.CommentsPerPage"), "30", additionalSettingsCategory);

			ParamsDefinition["MainPagePostCount"] = new BXParamText(GetMessageRaw("Param.MainPagePostCount"), "6", additionalSettingsCategory);
			ParamsDefinition["MainPageBlogCount"] = new BXParamText(GetMessageRaw("Param.MainPageBlogCount"), "6", additionalSettingsCategory);

			BXCategory guestsCategory = new BXCategory(GetMessageRaw("Category.Guests"), "guest_parameters", mainCategory.Sort + 100);
			ParamsDefinition["GuestEmail"] = new BXParamSingleSelection(GetMessageRaw("Param.GuestEmail"), "required", guestsCategory);
			ParamsDefinition["GuestCaptcha"] = new BXParamYesNo(GetMessageRaw("Param.GuestCaptcha"), true, guestsCategory);

			ParamsDefinition["UserProfileUrl"] = new BXParamText(GetMessageRaw("Param.UserProfileUrl"), "", urlCategory);
			ParamsDefinition["UserProfileEditUrl"] = new BXParamText(GetMessageRaw("Param.UserProfileEditUrl"), "", urlCategory);

		}
		protected override void LoadComponentDefinition()
		{
			BXParametersDefinition.SetPaging(ParamsDefinition, ClientID, BXParametersDefinition.PagingParamsOptions.DisablePreLoad | BXParametersDefinition.PagingParamsOptions.DisableShowAll);

			string csaId = ClientID;

			ParamsDefinition["EnableSEF"].ClientSideAction = new ParamClientSideActionGroupViewSwitch(csaId, "EnableSEF", "Sef", "NonSef");
			ParamsDefinition["SEFFolder"].ClientSideAction = new ParamClientSideActionGroupViewMember(csaId, "SEFFolder", new string[] { "Sef" });

			foreach (string id in new string[] {
				"BlogVariable", "CategoryVariable", "CommentVariable", "PostVariable", 
				"ActionVariable",  "PageVariable", "UserVariable"
			})
				ParamsDefinition[id].ClientSideAction = new ParamClientSideActionGroupViewMember(csaId, id, new string[] { "NonSef" });

			foreach (string id in new string[] {
				"NewPostTemplate", "PostListTemplate", "PostListPageTemplate", "DraftPostListTemplate", "DraftPostListPageTemplate",
				"PostTemplate", "PostPageTemplate", "PostEditTemplate",
				"CommentReadTemplate", "CommentEditTemplate",
				"UserProfileTemplate", "UserProfileEditTemplate",
				"NewBlogTemplate", "BlogEditTemplate", "BlogListTemplate", "BlogListPageTemplate",
				"CategoryBlogListTemplate", "CategoryBlogListPageTemplate",
				"NewPostListTemplate", "NewPostListPageTemplate", 
				"PopularPostListTemplate", "PopularPostListPageTemplate", 
				"DiscussPostListTemplate", "DiscussPostListPageTemplate"

			})
				ParamsDefinition[id].ClientSideAction = new ParamClientSideActionGroupViewMember(csaId, id, new string[] { "Sef" });


			DirectoryInfo info = new DirectoryInfo(BXPath.MapPath("~/bitrix/components/bitrix/blog/templates/.default/themes/"));
			if (info.Exists)
			{
				List<BXParamValue> values = new List<BXParamValue>();
				foreach (DirectoryInfo sub in info.GetDirectories())
				{
					if (!File.Exists(Path.Combine(sub.FullName, "style.css")))
						continue;

					string themeTitle = BXLoc.GetMessage("~/bitrix/components/bitrix/blog/templates/.default/themes/" + sub.Name + "/description", "Title");
					if (String.IsNullOrEmpty(themeTitle))
						themeTitle = sub.Name;

					values.Add(new BXParamValue(themeTitle, VirtualPathUtility.Combine("~/bitrix/components/bitrix/blog/templates/.default/themes/", sub.Name + "/style.css")));
				}
				ParamsDefinition["ColorCss"].Values = values;
			}

			ParamsDefinition["GuestEmail"].Values = new List<BXParamValue>(new BXParamValue[] {
				new BXParamValue(GetMessageRaw("GuestEmail.Hide"), ""),
				new BXParamValue(GetMessageRaw("GuestEmail.Show"), "visible"),
				new BXParamValue(GetMessageRaw("GuestEmail.Require"), "required")
			});
		}

		private string PrepareSefMode()
		{
			string sefFolder = Parameters.GetString("SEFFolder", "");

			ComponentCache["IndexUrlTemplate"] = CombineLink(sefFolder, "");
			ComponentCache["NewPostUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("NewPostTemplate"));
			ComponentCache["PostListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PostListTemplate"));
			ComponentCache["PostListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PostListPageTemplate"));
			ComponentCache["DraftPostListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("DraftPostListTemplate"));
			ComponentCache["DraftPostListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("DraftPostListPageTemplate"));
			ComponentCache["PostUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PostTemplate"));
			ComponentCache["PostPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PostPageTemplate"));
			ComponentCache["PostEditUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PostEditTemplate"));
			ComponentCache["CommentReadUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("CommentReadTemplate"));
			ComponentCache["CommentEditUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("CommentEditTemplate"));
			ComponentCache["UserProfileUrlTemplate"] = GetExternalUrlTemplate("UserProfileUrl") ?? CombineLink(sefFolder, Parameters.GetString("UserProfileTemplate"));
			ComponentCache["UserProfileEditUrlTemplate"] = GetExternalUrlTemplate("UserProfileEditUrl") ?? CombineLink(sefFolder, Parameters.GetString("UserProfileEditTemplate"));
			ComponentCache["NewBlogUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("NewBlogTemplate"));
			ComponentCache["BlogEditUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("BlogEditTemplate"));
			ComponentCache["BlogListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("BlogListTemplate"));
			ComponentCache["BlogListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("BlogListPageTemplate"));
			ComponentCache["CategoryBlogListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("CategoryBlogListTemplate"));
			ComponentCache["CategoryBlogListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("CategoryBlogListPageTemplate"));
			ComponentCache["NewPostListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("NewPostListTemplate"));
			ComponentCache["NewPostListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("NewPostListPageTemplate"));
			ComponentCache["PopularPostListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PopularPostListTemplate"));
			ComponentCache["PopularPostListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("PopularPostListPageTemplate"));
			ComponentCache["DiscussPostListUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("DiscussPostListTemplate"));
			ComponentCache["DiscussPostListPageUrlTemplate"] = CombineLink(sefFolder, Parameters.GetString("DiscussPostListPageTemplate"));

			return PrepareSefPage();
		}
		private string PrepareSefPage()
		{
			BXParamsBag<string> sefMap = new BXParamsBag<string>();

			sefMap.Add("post-edit.new", Parameters.GetString("NewPostTemplate"));
			sefMap.Add("post-edit.edit", Parameters.GetString("PostEditTemplate"));
			sefMap.Add("blog", Parameters.GetString("PostListTemplate"));
			sefMap.Add("blog.page", Parameters.GetString("PostListPageTemplate"));
			sefMap.Add("blog.draft", Parameters.GetString("DraftPostListTemplate"));
			sefMap.Add("blog.draft.page", Parameters.GetString("DraftPostListPageTemplate"));
			sefMap.Add("post", Parameters.GetString("PostTemplate"));
			sefMap.Add("post.page", Parameters.GetString("PostPageTemplate"));
			sefMap.Add("post.comment", Parameters.GetString("CommentReadTemplate"));
			//sefMap.Add("comment.edit", Parameters.GetString("CommentEditTemplate"));
			sefMap.Add("profile-view", Parameters.GetString("UserProfileTemplate"));
			sefMap.Add("profile-edit", Parameters.GetString("UserProfileEditTemplate"));
			sefMap.Add("blogs", Parameters.GetString("BlogListTemplate"));
			sefMap.Add("blogs.page", Parameters.GetString("BlogListPageTemplate"));
			sefMap.Add("blogs.category", Parameters.GetString("CategoryBlogListTemplate"));
			sefMap.Add("blogs.category.page", Parameters.GetString("CategoryBlogListPageTemplate"));
			sefMap.Add("blog-edit.new", Parameters.GetString("NewBlogTemplate"));
			sefMap.Add("blog-edit.edit", Parameters.GetString("BlogEditTemplate"));

			sefMap.Add("posts.new", Parameters.GetString("NewPostListTemplate"));
			sefMap.Add("posts.new.page", Parameters.GetString("NewPostListPageTemplate"));
			sefMap.Add("posts.popular", Parameters.GetString("PopularPostListTemplate"));
			sefMap.Add("posts.popular.page", Parameters.GetString("PopularPostListPageTemplate"));
			sefMap.Add("posts.discuss", Parameters.GetString("DiscussPostListTemplate"));
			sefMap.Add("posts.discuss.page", Parameters.GetString("DiscussPostListPageTemplate"));


			string code = BXSefUrlUtility.MapVariable(Parameters.GetString("SEFFolder", ""), sefMap, ComponentCache, "index", null, null);
			string page;
			string action;
			int i = code.IndexOf('.');
			if (i == -1)
			{
				page = code;
				action = "";
			}
			else
			{
				page = code.Remove(i);
				action = code.Substring(i + 1);
			}

			switch (page)
			{
				case "blog":
					switch (action)
					{
						case "draft":
						case "draft.page":
							ComponentCache["PagingIndexTemplate"] = ComponentCache["DraftPostListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["DraftPostListPageUrlTemplate"];
							ComponentCache["PublishMode"] = "Draft";
							break;
						default:
							ComponentCache["PagingIndexTemplate"] = ComponentCache["PostListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["PostListPageUrlTemplate"];
							ComponentCache["PublishMode"] = "Published";
							break;
					}
					break;

				case "post-edit":
					ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostUrlTemplate"];
					break;
				case "blog-edit":
					ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostListUrlTemplate"];
					break;
				case "blogs":
					switch (action)
					{
						case "category":
						case "category.page":
							ComponentCache["PagingIndexTemplate"] = ComponentCache["CategoryBlogListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["CategoryBlogListPageUrlTemplate"];
							break;
						default:
							ComponentCache["PagingIndexTemplate"] = ComponentCache["BlogListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["BlogListPageUrlTemplate"];
							break;
					}
					break;
				case "posts":
					switch (action)
					{
						case "popular":
						case "popular.page":
							ComponentCache["PagingIndexTemplate"] = ComponentCache["PopularPostListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["PopularPostListPageUrlTemplate"];
							ComponentCache["PostsSortBy"] = "ByViews";
							break;
						case "discuss":
						case "discuss.page":
							ComponentCache["PagingIndexTemplate"] = ComponentCache["DiscussPostListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["DiscussPostListPageUrlTemplate"];
							ComponentCache["PostsSortBy"] = "ByComments";
							break;
						default:
							ComponentCache["PagingIndexTemplate"] = ComponentCache["NewPostListUrlTemplate"];
							ComponentCache["PagingPageTemplate"] = ComponentCache["NewPostListPageUrlTemplate"];
							ComponentCache["PostsSortBy"] = "ByDate";
							Parameters["PeriodDays"] = "0";
							break;
					}
					break;
				case "profile-view":
				case "profile-edit":
					ComponentCache["ProfileFields"] = GetUserProfileFields();
					if (page == "profile-edit")
					{
						string url = GetExternalUrlTemplate("UserProfileEditUrl");
						if (url != null)
							RedirectTemplateUrl(url, ComponentCache);
						
						ComponentCache["PageTitle"] = GetMessageRaw("PageTitle.EditProfile");
						ComponentCache["RequiredProfileFields"] = GetRequiredUserProfileFields();
					}
					else
					{
						string url = GetExternalUrlTemplate("UserProfileUrl");
						if (url != null)
							RedirectTemplateUrl(url, ComponentCache);

						ComponentCache["PageTitle"] = GetMessageRaw("PageTitle.ViewProfile");
					}
					break;
			}

			return page;
		}

		private string PrepareNormalMode()
		{
			string filePath = Request.FilePath;
			string blogVar = UrlEncode(BlogVariable);
			string postVar = UrlEncode(PostVariable);
			string commentVar = UrlEncode(CommentVariable);
			string actionVar = UrlEncode(ActionVariable);
			string pageVar = UrlEncode(PageVariable);

			UriBuilder uri = new UriBuilder(BXSefUrlManager.CurrentUrl);
			uri.Query = null;
            ComponentCache["IndexUrlTemplate"] = uri.ToString();
			ComponentCache["NewPostUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#&{2}=newpost", filePath, blogVar, actionVar);
			ComponentCache["PostListUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#", filePath, blogVar);
			ComponentCache["PostListPageUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#&{2}=#PageId#", filePath, blogVar, pageVar);
			ComponentCache["DraftPostListUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#&{2}=draft", filePath, blogVar, actionVar);
			ComponentCache["DraftPostListPageUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#&{2}=draft&{3}=#PageId#", filePath, blogVar, actionVar, pageVar);
			ComponentCache["BlogEditUrlTemplate"] = String.Format("{0}?{1}=#BlogSlug#&{2}=edit", filePath, blogVar, actionVar);

			ComponentCache["PostUrlTemplate"] = String.Format("{0}?{1}=#PostId#", filePath, postVar);
			ComponentCache["PostPageUrlTemplate"] = String.Format("{0}?{1}=#PostId#&{2}=#PageId###comments", filePath, postVar, pageVar);
			ComponentCache["PostEditUrlTemplate"] = String.Format("{0}?{1}=#PostId#&{2}=edit", filePath, postVar, actionVar);
			ComponentCache["CommentReadUrlTemplate"] = String.Format("{0}?{1}=#PostId#&{2}=#CommentId###comment#CommentId#", filePath, postVar, commentVar);
			ComponentCache["CommentEditUrlTemplate"] = String.Format("{0}?{1}=#PostId#&{2}=#CommentId#&{3}=edit", filePath, postVar, commentVar, actionVar);

			ComponentCache["UserProfileUrlTemplate"] = GetExternalUrlTemplate("UserProfileUrl") ?? String.Format("{0}?{1}=#UserId#", filePath, UrlEncode(UserVariable));
			ComponentCache["UserProfileEditUrlTemplate"] = GetExternalUrlTemplate("UserProfileEditUrl") ?? String.Format("{0}?{1}=#UserId#&{2}=edit", filePath, UrlEncode(UserVariable), actionVar);

			ComponentCache["NewBlogUrlTemplate"] = String.Format("{0}?{1}=newblog", filePath, actionVar);
			ComponentCache["BlogListUrlTemplate"] = String.Format("{0}?{1}=blogs", filePath, actionVar);
			ComponentCache["BlogListPageUrlTemplate"] = String.Format("{0}?{1}=blogs&{2}=#PageId#", filePath, actionVar, pageVar);

			ComponentCache["CategoryBlogListUrlTemplate"] = String.Format("{0}?{1}=#CategoryId#", filePath, UrlEncode(CategoryVariable));
			ComponentCache["CategoryBlogListPageUrlTemplate"] = String.Format("{0}?{1}=#CategoryId#&{2}=#PageId#", filePath, UrlEncode(CategoryVariable), pageVar);

			ComponentCache["NewPostListUrlTemplate"] = String.Format("{0}?{1}=newposts", filePath, actionVar);
			ComponentCache["NewPostListPageUrlTemplate"] = String.Format("{0}?{1}=newposts&{2}=#PageId#", filePath, actionVar, pageVar);
			ComponentCache["PopularPostListUrlTemplate"] = String.Format("{0}?{1}=popular", filePath, actionVar);
			ComponentCache["PopularPostListPageUrlTemplate"] = String.Format("{0}?{1}=popular&{2}=#PageId#", filePath, actionVar, pageVar);
			ComponentCache["DiscussPostListUrlTemplate"] = String.Format("{0}?{1}=discuss", filePath, actionVar);
			ComponentCache["DiscussPostListPageUrlTemplate"] = String.Format("{0}?{1}=discuss&{2}=#PageId#", filePath, actionVar, pageVar);

			return PrepareNormalPage();
		}
		private string PrepareNormalPage()
		{
			string blogSlug = (Request.QueryString[BlogVariable] ?? String.Empty).ToLowerInvariant();
			int? commentId = ReadQueryInt(CommentVariable);
			int? categoryId = ReadQueryInt(CategoryVariable);
			int? postId = ReadQueryInt(PostVariable);
			int? pageId = ReadQueryInt(PageVariable);
			int? userId = ReadQueryInt(Parameters["UserVariable"]);

			string action = (Request.QueryString[ActionVariable] ?? String.Empty).ToLowerInvariant();

			ComponentCache["BlogSlug"] = blogSlug;
			ComponentCache["CategoryId"] = categoryId.ToString();
			ComponentCache["CommentId"] = commentId.ToString();
			ComponentCache["PostId"] = postId.ToString();
			ComponentCache["PageId"] = pageId.ToString();

			if (!String.IsNullOrEmpty(blogSlug))
			{
				switch (action)
				{
					case "newpost":
						ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostUrlTemplate"];
						return "post-edit";
					case "edit":
						ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostListUrlTemplate"];
						return "blog-edit";
					case "draft":
						ComponentCache["PagingIndexTemplate"] = ComponentCache["DraftPostListUrlTemplate"];
						ComponentCache["PagingPageTemplate"] = ComponentCache["DraftPostListPageUrlTemplate"];
						ComponentCache["PublishMode"] = "Draft";
						return "blog";
					default:
						ComponentCache["PagingIndexTemplate"] = ComponentCache["PostListUrlTemplate"];
						ComponentCache["PagingPageTemplate"] = ComponentCache["PostListPageUrlTemplate"];
						ComponentCache["PublishMode"] = "Published";
						return "blog";
				}
			}
			else if (postId != null)
			{
				switch (action)
				{
					case "edit":
						ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostUrlTemplate"];
						return "post-edit";
					default:
						return "post";
				}
			}
			else if (commentId != null)
			{
				switch (action)
				{
					//case "edit":
					//	return "comment-edit";
					default:
						return "post";
				}
			}
			else if (userId != null)
			{
				ComponentCache["UserId"] = userId.ToString();
				ComponentCache["ProfileFields"] = GetUserProfileFields();
				string url;
				switch (action)
				{
					case "edit":
						url = GetExternalUrlTemplate("UserProfileEditUrl");
						if (url != null)
							RedirectTemplateUrl(url, ComponentCache);

						ComponentCache["RequiredProfileFields"] = GetRequiredUserProfileFields();
						ComponentCache["PageTitle"] = GetMessageRaw("PageTitle.EditProfile");
						return "profile-edit";
					default:
						url = GetExternalUrlTemplate("UserProfileUrl");
						if (url != null)
							RedirectTemplateUrl(url, ComponentCache);

						ComponentCache["PageTitle"] = GetMessageRaw("PageTitle.ViewProfile");
						return "profile-view";
				}
			}
			else if (categoryId != null)
			{
				ComponentCache["PagingIndexTemplate"] = ComponentCache["CategoryBlogListUrlTemplate"];
				ComponentCache["PagingPageTemplate"] = ComponentCache["CategoryBlogListPageUrlTemplate"];
				return "blogs";
			}

			switch (action)
			{
				case "newblog":
					ComponentCache["RedirectUrlTemplate"] = ComponentCache["PostListUrlTemplate"];
					return "blog-edit";
				case "blogs":
					ComponentCache["PagingIndexTemplate"] = ComponentCache["BlogListUrlTemplate"];
					ComponentCache["PagingPageTemplate"] = ComponentCache["BlogListPageUrlTemplate"];
					return "blogs";
				case "newposts":
					ComponentCache["PagingIndexTemplate"] = ComponentCache["NewPostListUrlTemplate"];
					ComponentCache["PagingPageTemplate"] = ComponentCache["NewPostListPageUrlTemplate"];
					ComponentCache["PostsSortBy"] = "ByDate";
					Parameters["PeriodDays"] = "0";
					return "posts";
				case "popular":
					ComponentCache["PagingIndexTemplate"] = ComponentCache["PopularPostListUrlTemplate"];
					ComponentCache["PagingPageTemplate"] = ComponentCache["PopularPostListPageUrlTemplate"];
					ComponentCache["PostsSortBy"] = "ByViews";
					return "posts";
				case "discuss":
					ComponentCache["PagingIndexTemplate"] = ComponentCache["DiscussPostListUrlTemplate"];
					ComponentCache["PagingPageTemplate"] = ComponentCache["DiscussPostListPageUrlTemplate"];
					ComponentCache["PostsSortBy"] = "ByComments";
					return "posts";
			}

			return "index";
		}

		private string GetExternalUrlTemplate(string parameter)
		{
			string val = Parameters.GetString(parameter);
			return !BXStringUtility.IsNullOrTrimEmpty(val) ? val : null;
		}
		private string GetUserProfileFields()
		{
			return BXStringUtility.ListToCsv(new string[] {
				"Image",
				"DisplayName",
				"@" + GetMessageRaw("FieldGroup.PersonalData"),
				"BirthdayDate",
				"Gender",
				"LastName",
				"FirstName",
				"SecondName"
			});
		}
		private static string GetRequiredUserProfileFields()
		{
			return string.Empty;
		}
		private int? ReadQueryInt(string param)
		{
			string[] values = Request.QueryString.GetValues(param);
			if (values == null || values.Length == 0)
				return null;
			int i;
			if (!int.TryParse(values[0], out i))
				return null;
			return i;
		}
		private void Redirect(string url)
		{
			if (url.StartsWith("?"))
			{
				UriBuilder uri = new UriBuilder(BXSefUrlManager.CurrentUrl);
				uri.Query = url.Substring(1);
				url = uri.ToString();
			}
			Response.Redirect(url);
		}
	}

	public class BlogTemplate : BXComponentTemplate<BlogComponent>
	{
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			string css = Parameters.GetString("ColorCss");
			if (!BXStringUtility.IsNullOrTrimEmpty(css))
			{
				try
				{
					css = BXPath.ToVirtualRelativePath(css);
					if (BXSecureIO.FileExists(css))
						BXPage.RegisterStyle(css);
				}
				catch
				{
				}
			}
		}
	}
}