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

using System;
using CommunityServer.Components;
using System.Text.RegularExpressions;

namespace CommunityServer.Files.Components
{
	/// <summary>
	/// This class contains the properties that describe a Picture.  It inherits from the base class <see cref="Post"/>.
	/// </summary>
	public class Entry : Post, IThread, IComparable
	{

		#region Custom Properties

		/// <summary>
		/// This property defines the ContentType for the image, such as "image/jpeg" or "image/gif".
		/// </summary>
		public string ContentType
		{
			get { return GetExtendedAttribute( "ContentType" ); }
			set { SetExtendedAttribute( "ContentType", value); }
		}

		public int FileSize
		{
			get
			{
				string val = GetExtendedAttribute( "ImageSize" );
				if(val != string.Empty)
					return int.Parse(val);
				else
					return 0;
			}
			set { SetExtendedAttribute( "ImageSize", value.ToString() ); }
		}

		public bool EnableComments
		{
			get
			{
				string val = GetExtendedAttribute( "EnableComments" );
				if(val != string.Empty)
					return bool.Parse(val);
				else
					return Folders.GetFolder(this.SectionID).EnableComments;
			}
			set { SetExtendedAttribute( "EnableComments", value.ToString() ); }
		}

		public bool EnableRatings
		{
			get
			{
				string val = GetExtendedAttribute( "EnableRatings" );
				if(val != string.Empty)
					return bool.Parse(val);
				else
					return Folders.GetFolder(this.SectionID).EnableRatings;
			}
			set { SetExtendedAttribute( "EnableRatings", value.ToString() ); }
		}

		public bool EnableCommentNotification
		{
			get
			{
				string val = GetExtendedAttribute( "EnableCommentNotification" );
				if(val != string.Empty)
					return bool.Parse(val);
				else
					return Folders.GetFolder(this.SectionID).EnableCommentNotification;
			}
			set { SetExtendedAttribute( "EnableCommentNotification", value.ToString() ); }
		}

		public bool EnableEntryNotification
		{
			get
			{
				string val = GetExtendedAttribute( "EnableEntryNotification" );
				if(val != string.Empty)
					return bool.Parse(val);
				else
					return Folders.GetFolder(this.SectionID).EnableEntryNotification;
			}
			set { SetExtendedAttribute( "EnableEntryNotification", value.ToString() ); }
		}

		#endregion

		#region CompareTo

		// *********************************************************************
		//  CompareTo
		//
		/// <summary>
		/// All forums have a SortOrder property. CompareTo compares on SortOrder
		/// to sort the forums appropriately.
		/// </summary>
		// ********************************************************************/
		public int CompareTo(object value)
		{
			if(value == null) return 1;

			return this.SortOrder.CompareTo( ((Entry)value).SortOrder );
		}


		#endregion

		#region Post Implementation
		private Folder _gallery = null;
		public override Section Section
		{
			get
			{
				if(_gallery == null)
					_gallery = Folders.GetFolder(this.SectionID);

				return _gallery;
			}
			set
			{
				_gallery = value as Folder;
			}
		}
		#endregion

		#region IThread Privates
		string mostRecentAuthor = "";   // Most recent post author
		int mostRecentAuthorID = 0;
		int mostRecentPostID = 0;       // Most recent post id
		int authorID = 0;
//		int ratingSum = 0;
//		int totalRatings = 0;
		#endregion

		#region IThread Public Properties

		ThreadStatus status = ThreadStatus.NotSet;
		public ThreadStatus Status 
		{
			get { return status; }
			set { status = value; }
		}

		public int AuthorID 
		{
			get 
			{
				return authorID;
			}
			set 
			{
				authorID = value;
			}
		}

		// *********************************************************************
		//
		//  IsPopular
		//
		/// <summary>
		/// If thread has activity in the last 2 days and > 20 replies
		/// </summary>
		//
		// ********************************************************************/
		public bool IsPopular 
		{
			get 
			{ 
				if ((ThreadDate < DateTime.Now.AddDays(FileGalleryConfiguration.GetConfig().PopularPostLevelDays)) && ( (Replies > FileGalleryConfiguration.GetConfig().PopularPostLevelPosts) || (Views > FileGalleryConfiguration.GetConfig().PopularPostLevelViews) ))
					return true;

				return false;
			}
		}
        
        
		// *********************************************************************
		//
		//  IsAnnouncement
		//
		/// <summary>
		/// If post is locked and post date > 2 years
		/// </summary>
		//
		// ********************************************************************/
		public bool IsAnnouncement 
		{
			get 
			{ 
				if ((StickyDate > DateTime.Now.AddYears(2)) && (IsLocked))
					return true;
				else
					return false;
			}
		}


		bool isSticky = false;
		public bool IsSticky 
		{
			get 
			{
				return isSticky;
			}
			set 
			{
				isSticky = value;
			}
		}

		DateTime stickyDate = DateTime.Now.AddYears(-25);
		public DateTime StickyDate 
		{
			get 
			{
				return stickyDate;
			}
			set 
			{
				stickyDate = value;
			}
		}


		// *********************************************************************
		//
		//  MostRecentPostAuthor
		//
		/// <summary>
		/// The author of the most recent post in the thread.
		/// </summary>
		//
		// ********************************************************************/
		public string MostRecentPostAuthor 
		{
			get 
			{ 
				return mostRecentAuthor; 
			}
			set 
			{ 
				mostRecentAuthor = value; 
			}
		}

		public int MostRecentPostAuthorID 
		{
			get 
			{
				return mostRecentAuthorID;
			}
			set 
			{
				mostRecentAuthorID = value;
			}
		}

		public string PreviewBody 
		{
			get 
			{
				return Transforms.StripForPreview(base.Body);
			}
		}

		// *********************************************************************
		//
		//  MostRecentPostID
		//
		/// <summary>
		/// The post id of the most recent post in the thread.
		/// </summary>
		//
		// ********************************************************************/
		public int MostRecentPostID 
		{
			get 
			{ 
				return mostRecentPostID; 
			}
			set 
			{ 
				mostRecentPostID = value; 
			}
		}

		#endregion

		public string AuthorURL
		{
			get
			{
				return SiteUrls.Instance().UserProfile(this.AuthorID); 
			}
		}

		public string ViewPostURL
		{
			get
			{
				return FileGalleryUrls.Instance().ViewEntry(this.Section.ApplicationKey, this.PostID);
			}
		}

		private int settingsID = -1;
		public int SettingsID
		{
			get { return settingsID; }
			set { settingsID = value; }
		}

		private string[] categories;
		/// <summary>
		/// list of categories this post was made to
		/// </summary>
		public string[] Categories
		{
			get{return categories;}
			set{categories = value;}
		}

		private int downloads = 0;
		public int Downloads
		{
			get { return downloads; }
			set { downloads = value; }
		}

		public FileGalleryPostType FileGalleryPostType
		{
			get { return FileGalleryPostType.File; }
		}

		public bool GetIsTracked(int userID)
		{
			return ThreadTracking.IsTracked(this.ThreadID,userID);
		}

		public string DisplayName
		{
			get
			{
				if (this.User != null)
					return this.User.DisplayName;
				else
				{
					this.User = Users.GetUser(this.UserID, this.Username, false, true);
					if (this.User != null && this.User.UserID > 0)
						return this.User.DisplayName;
					else
						return this.Username;
				}
			}
		}


		#region Static Methods

		public static string GetPreviewImageUrl(Entry entry, CSContext context, FileThumbnailSize size)
		{
			string url = String.Empty;

			if (context.IsWebRequest)
			{
				try
				{
					string path = context.MapPath("~/utility/filethumbnails/");
					string fileExtension = GetExtension(entry.AttachmentFilename);
					string fileModifier = size == FileThumbnailSize.Normal ? "" : "-" + size.ToString();

					if (fileExtension != "" && System.IO.File.Exists(path + fileExtension + fileModifier + ".gif"))
						url = context.Context.Response.ApplyAppPathModifier("~/utility/filethumbnails/" + fileExtension + fileModifier + ".gif");
					else if (System.IO.File.Exists(path + "unknown" + fileModifier + ".gif"))
						url = context.Context.Response.ApplyAppPathModifier("~/utility/filethumbnails/unknown" + fileModifier + ".gif");
				}
				catch
				{
				}
			}

			return url;
		}

		public static string GetPreviewImageUrl(Entry entry, CSContext context)
		{
			return GetPreviewImageUrl(entry, context, FileThumbnailSize.Normal);
		}

		private static Regex ExtensionRegex = new Regex("^.+\\.(?<extension>[^\\.]*)$");
		public static string GetExtension(string fileName)
		{
			Match m = ExtensionRegex.Match(fileName);
			if (m != null && m.Success)
				return m.Groups["extension"].Value;
			else
				return "";
		}

		#endregion
	}

	public enum FileThumbnailSize
	{
		Normal,
		Small
	}
}
