//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections;
using System.Web;
using System.Web.Caching;
using CommunityServer.Components;
using CommunityServer.Files.Components;

namespace CommunityServer.Files
{
    /// <summary>
    /// Manager class for the <see cref="Folder"/> objects.  This class cannot be instanciated, it contains all static methods.
    /// </summary>
    public class EntryComments
    {
        // Do not allow the class to be instanciated.
        private EntryComments() { }

		public static void FormatPost(EntryComment comment)
		{
			comment.FormattedBody = HttpUtility.HtmlEncode(comment.Body);
			CSEvents.PrePost(comment,ObjectState.Create,ApplicationType.FileGallery);
			CSEvents.BeforePost(comment,ObjectState.Create,ApplicationType.FileGallery);
		}

		public static EntryComment UpdateComment(EntryComment comment, int userID)
		{
			comment.FormattedBody = HttpUtility.HtmlEncode(comment.Body);
			CSEvents.PrePost(comment,ObjectState.Update,ApplicationType.FileGallery);
			CSEvents.BeforePost(comment,ObjectState.Update,ApplicationType.FileGallery);

			// Update it in the database
			FileGalleryDataProvider.Instance().UpdateComment(comment, userID, comment.GetExtendedAttribute("Notes"));

			// Clear cache
			ClearCache(-1);

			CSEvents.AfterPost(comment,ObjectState.Update,ApplicationType.FileGallery);

			return comment;
		}

        public static EntryComment CreateComment(int pictureID, EntryComment comment)
        {
        	Entry entry = Entries.GetEntry(pictureID);

			if (Globals.IsNullorEmpty(comment.Subject))
				comment.Subject = ResourceManager.GetString("CreateEditPost_ReplyPrePend") + entry.Subject;

            // Setup the ThreadID and parent PostID
            comment.ThreadID = entry.ThreadID;
            comment.ParentID = entry.PostID;

			FormatPost(comment);

            // Submit it to the database
        	FileGalleryDataProvider.Instance().CreateComment(comment);

			// Clear cache
			ClearCache(-1);

			CSEvents.AfterPost(comment,ObjectState.Create,ApplicationType.FileGallery);
            
            // Return it for use with sending the email
            return comment;
        }

        public static void ApproveComment(int postID, int parentID) 
        {
        	FileGalleryDataProvider.Instance().ApprovePost(postID, CSContext.Current.User.UserID);
			ClearCache(parentID);
        }

        public static void DeleteComment(int postID, int parentID) 
        {
        	FileGalleryDataProvider.Instance().DeletePost(postID, CSContext.Current.User.UserID);
			ClearCache(parentID);
        }

		public static EntryComment GetComment(int commentID, bool cacheable)
		{
			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			query.PostID = commentID;
			query.ApplicationPostType = FileGalleryPostType.Comment;
			query.OnlyApproved = false;
			query.OnlyUnapproved = false;
			query.IsCacheable = cacheable;
		
			ThreadSet threads = GetComments(query, cacheable);
			if (threads.TotalRecords > 0)
				return (EntryComment) threads.Threads[0];
			else
				return null;
		}

        public static EntryComment GetComment(int categoryID, int pictureID, int commentID)
        {
        	ArrayList comments = GetComments(pictureID);

            // Loop through all the comments and find the right one
            foreach(EntryComment comment in comments)
                if(comment.PostID == commentID)
                    return comment;

            // None were found, so throw a resource not found exception
            throw new CSException(CSExceptionType.PostNotFound, "Comment not found: " + commentID);
        }

        public static ArrayList GetComments(int pictureID)
        {
            return GetComments(pictureID, true);
        }

		public static void ClearCache(int entryID)
		{
			CSContext cntx = CSContext.Current;
			CSCache.RemoveByPattern("CommentQuery\\-.*");
			cntx.Items.Remove(string.Format("Comments-Site:{0}EntryID:{1}ApprovedOnly:{2}", cntx.SiteSettings.SettingsID, entryID, true));
			cntx.Items.Remove(string.Format("Comments-Site:{0}EntryID:{1}ApprovedOnly:{2}", cntx.SiteSettings.SettingsID, entryID, false));
		}

        public static ArrayList GetComments(int entryID, bool allowUnapproved)
        {
        	CSContext cntx = CSContext.Current;
        	string cacheKey = string.Format("Comments-Site:{0}EntryID:{1}ApprovedOnly:{2}", cntx.SiteSettings.SettingsID, entryID, allowUnapproved);
            ArrayList comments = cntx.Items[cacheKey] as ArrayList;
            if(comments == null)
            {
                comments = FileGalleryDataProvider.Instance().GetComments(entryID, allowUnapproved);
                cntx.Items.Add(cacheKey, comments);
            }
            return comments;
        }

		public static ThreadSet GetComments(FileGalleryThreadQuery query)
		{
			return GetComments(query, true);
		}

		public static ThreadSet GetComments(FileGalleryThreadQuery query, bool cacheable)
		{
			return GetComments(query, cacheable, false);
		}

		public static ThreadSet GetComments(FileGalleryThreadQuery query, bool cacheable, bool isAggregate)
		{
			string key = cacheable ? string.Format("CommentQuery-{0}{1}", query.Key, CSContext.Current.RolesCacheKey) : null;
			ThreadSet ts = null;

			if(cacheable)
				ts = CSCache.Get(key) as ThreadSet;

			if(ts == null)
			{
				ts = FileGalleryDataProvider.Instance().GetComments(query);

				if(cacheable)
					CSCache.Insert(key, ts, CSCache.MinuteFactor * 5, isAggregate ? CacheItemPriority.High : CacheItemPriority.BelowNormal);
			}

			return ts;
		}




    }
}
