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

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using CommunityServer.Blogs.Components;
using CommunityServer.Files.Components;
using CommunityServer.Galleries.Components;
using CommunityServer.Discussions.Components;
using CommunityServer.Mail.Common.Components;
using Telligent.Registration;
using CP = CommunityServer.ControlPanel.Components;
using CommunityServer.ControlPanel.Controls;

namespace CommunityServer.ControlPanel
{
	/// <summary>
	/// Summary description for _Default.
	/// </summary>
	public class ControlPanelHomePage : System.Web.UI.Page
	{
		#region Child Controls
		
		protected Literal Version;
		protected Repeater Announcements;
		protected Control MembershipArea, MyBlogsArea, BlogAdministrationArea, MyPhotosArea, PhotoAdministrationArea, MyFilesArea, FileAdministrationArea, ForumModerationArea, ForumAdministrationArea, SystemAdministrationArea, ReaderAdministrationArea;

		protected Literal BlogAdministrationDescription, PhotoAdministrationDescription, FileAdministrationDescription, ForumsModerationDescription, ForumsAdministrationDescription, MembershipDescription, ReaderAdministrationDescription;

		protected Control MyBlogsNewPostArea, MyBlogsNewPostByEmailArea, MyBlogsReviewCommentsArea, MyBlogsManageArea;
		protected HyperLink MyBlogsNewPost, MyBlogsNewPostByEmail, MyBlogsReviewComments, MyBlogsManage;

		protected Control MyPhotosNewPostArea, MyPhotosReviewCommentsArea, MyPhotosManageArea;
		protected HyperLink MyPhotosNewPost, MyPhotosReviewComments, MyPhotosManage;

		protected Control MyFilesNewFileArea, MyFilesReviewFilesArea, MyFilesReviewCommentsArea, MyFilesManageArea;
		protected HyperLink MyFilesNewFile, MyFilesReviewFiles, MyFilesReviewComments, MyFilesManage;
		protected HyperLink NewVersionAvailable;

		#endregion

		CSContext csContext = null;
		User currentUser = null;

		override protected void OnInit(EventArgs e)
		{
			this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
			Authorize();	
			this.Load += new System.EventHandler(this.Page_Load);
			base.OnInit(e);
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			csContext = CSContext.Current;
			currentUser = csContext.User;
			if ( !Page.IsPostBack ) 
			{
				this.DataBind();
			}
		}

		protected virtual void Authorize()
		{
			if(!CSContext.Current.IsAuthenticated)
				Response.Redirect(Globals.GetSiteUrls().Login);
			UsersOnline.PrivateLocation();
		}

		public override void DataBind() 
		{
			base.DataBind();

			this.Version.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_Version_Description"), SiteStatistics.CommunityServerVersion.ToString()); 
			
			if (CommunityServer.Configuration.CSConfiguration.GetConfig().EnableLatestVersionCheck && SiteStatistics.NewVersionAvailable(SiteStatistics.MostRecentVersion))
			{
				this.NewVersionAvailable.Visible = true;
				this.NewVersionAvailable.Text = CP.ResourceManager.GetString("CP_Dashboard_Version_NewVersionAvailable");
				this.NewVersionAvailable.NavigateUrl = "http://communityserver.org/";
			}
			else
				this.NewVersionAvailable.Visible = false;

			this.Announcements.DataSource = CommunityServer.ControlPanel.Components.AnnouncementsFeed.GetAnnouncements();
			this.Announcements.DataBind();

			if (ApplicationSet.Applications[ApplicationType.Weblog].Enabled)
			{
			#region My Blog(s)

			Weblog blog = GetWeblog();
			if (blog != null)
			{
				MyBlogsNewPost.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyBlogs_NewPost"), blog.Name);
				MyBlogsReviewComments.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyBlogs_ReviewComments"), blog.Name);
				MyBlogsManage.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyBlogs_Manage"), blog.Name);

				if (csContext.SiteSettings.EnableMailGateway)
				{
					MailingList list = MailingLists.GetMailingList(blog.SectionID);
					if(list != null)
					{
						if(list.IsMailingList)
						{
							MyBlogsNewPostByEmailArea.Visible = true;
							MyBlogsNewPostByEmail.NavigateUrl = "mailto:" + list.DetermineEmailAddress();
							MyBlogsNewPostByEmail.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyBlogs_NewPostByEmail"), blog.Name);
						}
					}
				}
			}
			else
			{
				MyBlogsNewPostArea.Visible = false;
				MyBlogsNewPostByEmailArea.Visible = false;
				MyBlogsReviewCommentsArea.Visible = false;
				MyBlogsManageArea.Visible = false;
			}

			#endregion

			#region Blog Administration

			if (currentUser.IsBlogAdministrator)
			{
				BlogAdministrationArea.Visible = true;

				int postCount = 0;
				int commentCount = 0;
				ArrayList blogs = CommunityServer.Blogs.Components.Weblogs.GetWeblogs(true, true, false);
				int blogCount = blogs.Count;
				foreach (Weblog b in blogs)
				{
					postCount += b.PostCount;
					commentCount += b.CommentCount;
				}

				BlogAdministrationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_BlogAdministration_Description"), postCount, commentCount, blogCount);
			}
			else
				BlogAdministrationArea.Visible = false;

			#endregion
			}
			else
			{
				MyBlogsArea.Visible = false;
				BlogAdministrationArea.Visible = false;
			}

			if (ApplicationSet.Applications[ApplicationType.Gallery].Enabled)
			{
			#region My Photo(s)

			Gallery gallery = GetGallery();
			if (gallery != null)
			{
				MyPhotosNewPost.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyPhotos_NewPhoto"), gallery.Name);
				MyPhotosReviewComments.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyPhotos_ReviewComments"), gallery.Name);
				MyPhotosManage.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyPhotos_Manage"), gallery.Name);
			}
			else
			{
				MyPhotosNewPostArea.Visible = false;
				MyPhotosReviewCommentsArea.Visible = false;
				MyPhotosManageArea.Visible = false;
			}

			#endregion

			#region Photo Administration

			if (currentUser.IsGalleryAdministrator)
			{
				PhotoAdministrationArea.Visible = true;

				int postCount = 0;
				int commentCount = 0;
				ArrayList galleries = CommunityServer.Galleries.Galleries.GetGalleries(csContext.User.UserID, true, true, false);
				int galleryCount = galleries.Count;
				foreach (Gallery g in galleries)
				{
					postCount += g.PostCount;
					commentCount += g.CommentCount;
				}

				PhotoAdministrationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_PhotoAdministration_Description"), postCount, commentCount, galleryCount);
			}
			else
				PhotoAdministrationArea.Visible = false;

			#endregion
			}
			else
			{
				MyPhotosArea.Visible = false;
				PhotoAdministrationArea.Visible = false;
			}

			if (ApplicationSet.Applications[ApplicationType.FileGallery].Enabled)
			{
			#region My File(s)

			Folder folder = GetFolder();
			if (folder != null)
			{
				MyFilesNewFile.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyFiles_NewFile"), folder.Name);
				MyFilesReviewFiles.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyFiles_ReviewFiles"), folder.Name);
				MyFilesReviewComments.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyFiles_ReviewComments"), folder.Name);
				MyFilesManage.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_MyFiles_Manage"), folder.Name);
			}
			else
			{
				MyFilesNewFileArea.Visible = false;
				MyFilesReviewFilesArea.Visible = false;
				MyFilesReviewCommentsArea.Visible = false;
				MyFilesManageArea.Visible = false;		
			}

			#endregion

			#region File Administration

			if (currentUser.IsFileAdministrator)
			{
				FileAdministrationArea.Visible = true;

				int postCount = 0;
				int commentCount = 0;
				Hashtable folders = CommunityServer.Files.Components.Folders.GetFolders(csContext, csContext.UserID, true, true, false, true);
				int folderCount = folders.Count;
				foreach (Folder f in folders.Values)
				{
					postCount += f.TotalThreads;
					commentCount += f.TotalPosts - f.TotalThreads;
				}

				FileAdministrationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_FileAdministration_Description"), postCount, commentCount, folderCount);
			}
			else
				FileAdministrationArea.Visible = false;

			#endregion
			}
			else
			{
				MyFilesArea.Visible = false;
				FileAdministrationArea.Visible = false;
			}

			if (ApplicationSet.Applications[ApplicationType.Forum].Enabled)
			{
			#region Forums Moderation

			if (currentUser.IsForumAdministrator || currentUser.IsModerator)
			{
				ForumModerationArea.Visible = true;

				int totalPosts = 0;
				foreach (CommunityServer.Discussions.Components.Forum f in CommunityServer.Discussions.Controls.Moderate.GetForumsToModerate())
				{
					totalPosts += f.PostsToModerate;
				}

				ForumsModerationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_ForumsModeration_Description"), Response.ApplyAppPathModifier("~/ControlPanel/Moderation/"), totalPosts.ToString());
			}
			else
				ForumModerationArea.Visible = false;

			#endregion

			#region Forums Administration

			if (currentUser.IsForumAdministrator)
			{
				ForumAdministrationArea.Visible = true;

				int threadCount = 0;
				ArrayList forums = CommunityServer.Discussions.Components.Forums.GetForums(true, true, false, false);
				int forumCount = forums.Count - 1; // -1 is to remove private forum
				foreach (Forum f in forums)
				{
					threadCount += Math.Max(0, f.TotalThreads); // by default, total threads = -1
				}

				ForumsAdministrationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_ForumsAdministration_Description"), threadCount, forumCount);
			}
			else
				ForumAdministrationArea.Visible = false;

			#endregion
			}
			else
			{
				ForumModerationArea.Visible = false;
				ForumAdministrationArea.Visible = false;
			}

			#region Reader Administration

			if (ApplicationSet.Applications[ApplicationType.FeedReader].Enabled && currentUser.IsReaderAdministrator)
			{
				ReaderAdministrationArea.Visible = true;

				int feedCount = CommunityServer.Reader.Components.Feeds.GetAllFeeds(0).Count;
				int userCount = CommunityServer.Reader.Components.Feeds.GetUsers().Count;

				ReaderAdministrationDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_ReaderAdministration_Description"), userCount, feedCount);
			}
			else
				ReaderAdministrationArea.Visible = false;

			#endregion

			#region System Administration

			if (currentUser.IsAdministrator)
			{
				SystemAdministrationArea.Visible = true;
			}
			else
				SystemAdministrationArea.Visible = false;

			#endregion

			#region Membership

			if (currentUser.IsMembershipAdministrator)
			{
				MembershipArea.Visible = true;

				UserQuery query = new UserQuery();
				query.IncludeHiddenUsers = true;
				query.Status = UserAccountStatus.ApprovalPending;

				MembershipDescription.Text = string.Format(CP.ResourceManager.GetString("CP_Dashboard_Membership_Description"), Users.UserCount(query,true).ToString());
			}
			else
				MembershipArea.Visible = false;

			#endregion
		}

		#region Helper Methods

		protected string CreateApplicationCookieName(string app)
		{
			return string.Format("{0}_{1}_{2}", csContext.SettingsID,csContext.User.Username,app);
		}

		protected Weblog GetWeblog()
		{
			Weblog weblog = null;

			HttpCookie cookie = csContext.Context.Request.Cookies[CreateApplicationCookieName("weblog")];
			if(cookie != null)
			{
				if(!Globals.IsNullorEmpty(cookie.Values["BlogID"]))
				{
					int bid = Int32.Parse(cookie.Values["BlogID"]);
					try
					{
						weblog = Weblogs.GetWeblog(bid,true,false);
					}
					catch{}
				}
			}
					
			if(weblog == null)
			{
				ArrayList blogs = Weblogs.GetWeblogs(true,false,false);
				blogs = Sections.FilterByAccessControl(blogs,Permission.Post,csContext.User);

				if(blogs != null && blogs.Count == 1)
					weblog = blogs[0] as Weblog;
			}

			return weblog;
		}

		protected Gallery GetGallery()
		{
			Gallery gallery = null;

			HttpCookie cookie = csContext.Context.Request.Cookies[CreateApplicationCookieName("pg")];
			if(cookie != null)
			{
				if(!Globals.IsNullorEmpty(cookie.Values["GalleryID"]))
				{
					int gid = Int32.Parse(cookie.Values["GalleryID"]);
					try
					{
						gallery = CommunityServer.Galleries.Galleries.GetGallery(gid, true); //ignore permissions = false);
					}
					catch{}
				}
			}
					
			if(gallery == null)
			{
				ArrayList galleries = CommunityServer.Galleries.Galleries.GetGalleries(true,false); //ignore permissions = false);
				galleries = Sections.FilterByAccessControl(galleries,Permission.Post,csContext.User);

				if(galleries != null && galleries.Count == 1)
					gallery = galleries[0] as Gallery;
			}

			return gallery;
		}

		protected Folder GetFolder()
		{
			Folder folder = null;

			HttpCookie cookie = csContext.Context.Request.Cookies[CreateApplicationCookieName("files")];
			if(cookie != null)
			{
				if(!Globals.IsNullorEmpty(cookie.Values["FolderID"]))
				{
					int fid = Int32.Parse(cookie.Values["FolderID"]);
					try
					{
						folder = Folders.GetFolder(fid,true);
					}
					catch{}
				}
			}
					
			if(folder == null)
			{
				ArrayList folders = Folders.GetFolders(true,false);
				folders = Sections.FilterByAccessControl(folders,Permission.Administer,csContext.User);

				if(folders != null && folders.Count == 1)
					folder = folders[0] as Folder;
			}

			return folder;
		}

		#endregion
	}
}
