using System;
using CommunityServer.Components;
using System.Collections;
using CommunityServer.Blogs.Components;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Summary description for InlineTagEditor.
	/// </summary>
	public class InlineTagEditor : CommunityServer.Controls.InlineTagEditor
	{
		CSContext csContext = CSContext.Current;

		public override void SaveTags(int postID, string[] tags)
		{
			if (this.IsEditable(postID))
			{
				WeblogPost post = WeblogPosts.GetPost(postID, true, false, false);				
				post.Categories = tags;
				WeblogPosts.Update(post);
				PostCategories.ExpireCategoryCache(this.Weblog.SectionID);
			}
		}

		public override string GetUrl(string tag)
		{
			return BlogUrls.Instance().TagsBrowser(this.Weblog.ApplicationKey, new string[] { tag });
		}

		public override bool IsEditable (int postID)
		{
			return IsEditable();
		}

		public override bool IsEditable()
		{
			return Permissions.ValidatePermissions(this.Weblog, Permission.Post, csContext.User);
		}

		Weblog _weblog = null;
		public Weblog Weblog
		{
			get
			{
				if(_weblog == null)
				{
					string appKey = csContext.ApplicationKey;
					if(appKey == null)
						appKey = WeblogConfiguration.Instance().DefautApplicationKey;

					_weblog = Weblogs.GetWeblog(appKey,true);
				}

				return _weblog;
			}
			set
			{
				_weblog = value;
				_availableTags = null;
			}
		}

		string[] _availableTags = null;
		public override string[] AvailableTags 
		{ 
			get
			{
				if (_availableTags == null)
				{
					ArrayList allTags = PostCategories.GetCategories(this.Weblog.SectionID, true, false);
					ArrayList availableTags = new ArrayList();
					foreach (PostCategory pc in allTags)
					{
						availableTags.Add(pc.Name);
					}

					_availableTags = (string[]) availableTags.ToArray(typeof(string));
				}

				return _availableTags;
			}
		}
	}
}
