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

using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{

	public class PictureDetails : GalleryThemedControl
	{

		#region Public Properties

		private GalleryPost dataSource;
		public GalleryPost DataSource
		{
			get { return dataSource; }
			set { dataSource = value; }
		}

		#endregion

		#region Child Controls

		private IText Name;
		private IText Description;
		private GalleryImage detailsImage;
		private IText PostAuthor;
		private IText ViewCount;
		private IText TotalComments;
		private EntryComments comments;

		private HyperLink OriginalLink;
		private HyperLink ViewPictureLink;
		private HyperLink OrderLink;
		private ITrackedThread TrackingButton;

		private PostPager pager;
		private Panel pagerPanel;
		private CurrentPage currentPage;
		private TrackbackMarkUp tb = null;
		private InlineTagEditorPanel InlineTagEditor;
		#endregion

		private bool controlHasBound = false;
		private CSContext cSContext;

		#region Skin

		protected override void AttachChildControls()
		{
			Name = FindText( "Name" );
			Description = FindText( "Description" );
			detailsImage = (GalleryImage)FindControl( "detailsImage" );
			PostAuthor = FindText("PostAuthor");
			ViewCount = FindText( "ViewCount" );
			TotalComments = FindText( "TotalComments" );
		    comments = (EntryComments)FindControl( "EntryComments" );
			OriginalLink = (HyperLink)FindControl( "OriginalLink" );
			ViewPictureLink = (HyperLink)FindControl( "ViewPictureLink" );
			OrderLink = (HyperLink)FindControl( "OrderLink" );
			TrackingButton =  (ITrackedThread)FindControl( "TrackingButton" );
			pager = (PostPager) FindControl("Pager");
			pagerPanel = (Panel) FindControl("PagerPanel");
			currentPage = (CurrentPage) FindControl("CurrentPage");
			tb = new TrackbackMarkUp();
			InlineTagEditor = (InlineTagEditorPanel) FindControl("InlineTagEditorPanel");

			cSContext = CSContext.Current;
		}



		#endregion

		#region Event Overrides

		protected override void OnLoad(System.EventArgs e)
		{
            AjaxManager.Register(this,"PictureDetails");
			base.OnLoad(e);
			this.DataBind();
		}

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

		#endregion

		private void BindData()
		{
			if(DataSource == null)
				DataSource = GalleryPosts.GetPicture(cSContext.PostID, false, true); //return;

			GalleryThreadQuery query = new GalleryThreadQuery();
			query.PostID = DataSource.PostID;
			query.IncludeCategories = true;
			query.ReturnFullThread = true;
			query.SectionID = CurrentGallery.SectionID;

			PostSet ps =  GalleryPosts.GetPostSet(query);
			if(comments != null)
			{
				if(CurrentGallery.EnableCommentsDefault && DataSource != null)
				{
					if(ps != null)
					{
						comments.DataSource =  ps;
					}
					
					comments.CommentFormDataSource = DataSource;
					comments.DataBind();

				}
				else
				{
					comments.Visible = false;
				}
			}

			if(TrackingButton != null)
			{
				DataSource.IsTracked = ThreadTracking.IsTracked(DataSource.ThreadID, CurrentUser.UserID);
				TrackingButton.ThreadID = DataSource.ThreadID;
			}


			if(pager!= null)
			{
				//Direct navigation
				// Set up the query
				GalleryThreadQuery pagerQuery = new GalleryThreadQuery();
				pagerQuery.SectionID = CurrentGallery.SectionID;
				pagerQuery.CategoryID = cSContext.CategoryID;
				pagerQuery.ApplicationPostType = GalleryPostType.Image;
				pagerQuery.IncludePageIndex = true;

				//For CS 1.2 we are dropping the option to let the user sort
				//GalleryUserCookie userCookie = new GalleryUserCookie(CSContext.Current.User);
				//pagerQuery.SortBy = userCookie.ThreadSortBy;
				//pagerQuery.SortOrder = userCookie.ThreadSortOrder;

				pagerQuery.SortBy = Galleries.GetGallery(cSContext.ApplicationKey).ThreadSortBy;
				pagerQuery.SortOrder = Galleries.GetGallery(cSContext.ApplicationKey).ThreadSortOrder;

				ThreadSet ts = GalleryPosts.GetPictures(pagerQuery);
				pager.PageSize = 1;

				if(cSContext.CategoryID > 0)
					pager.UrlPattern = Globals.GetSiteUrls().UrlData.FormatUrl("gallery_ViewPicture_Category", cSContext.ApplicationKey,cSContext.CategoryID,"{0}"); 
				else
					pager.UrlPattern = Globals.GetSiteUrls().UrlData.FormatUrl("gallery_ViewPicture_Gallery",cSContext.ApplicationKey,"{0}");  
			
				//pager.PageSize = pagerQuery.PageSize;

				pager.PostIndex = ts.PageIndex;
				pager.PageIndex = pager.GetPage(cSContext.PostID);
				pager.TotalRecords = ts.TotalRecords;
				if(currentPage != null)
				{
					currentPage.TotalRecords = ts.TotalRecords;
					currentPage.TotalPages = pager.CalculateTotalPages();
					currentPage.PageIndex = pager.PageIndex;
				}
				if(pagerPanel != null)
				{
					if(currentPage != null)
						pagerPanel.Visible = (currentPage.TotalPages > 1);
					else
						pagerPanel.Visible = (ts.TotalRecords > 1);
					//pagerPanel.DataBind();
				}


			}
			
			if(DataSource != null)
			{
				//make sure we only render posts where they are supposed to be
				if(CanUserView(DataSource)) 
				{
			
					if(DataSource == null)
						DataSource = GalleryPosts.GetPicture(cSContext.PostID); //return;


					if(DataSource == null)
						Globals.Return404(Context);


					// Main information
                    if(this.Name != null)
                    {
                        Name.Text = DataSource.Subject;
                        InLinePictureTextEditor picSubject= Name as InLinePictureTextEditor;
                        if(picSubject != null && Permissions.ValidatePermissions(this.CurrentGallery,Permission.Post,this.CurrentUser))
                        {
                            picSubject.AjaxClientID = this.ClientID;
                            picSubject.AjaxFunction = string.Format("PictureDetails.UpdatePictureTitle('{0}',this.innerHTML,null);",this.ClientID);

                        }
                    }//
                    if(this.Description != null)
                    {
                        Description.Text = DataSource.RenderedBody(PostTarget.Web);//.Replace("\n", "<br/>");

                        InLinePictureTextEditor picDescription = Description as InLinePictureTextEditor;
                        if(picDescription != null && Permissions.ValidatePermissions(this.CurrentGallery,Permission.Post,this.CurrentUser))
                        {
                            picDescription.AjaxClientID = this.ClientID;
                            picDescription.AjaxFunction = string.Format("PictureDetails.UpdatePictureDescription('{0}',this.innerHTML,null);",this.ClientID);

                        }
                    }
					if(DataSource.HasCategories)
						Head.AddMetaTag("keywords", string.Join(",", DataSource.Categories), Context );

					string excerpt = null;
					if(DataSource.HasExcerpt)
						excerpt = DataSource.Excerpt;
					else
						excerpt = DataSource.RenderedBody(PostTarget.Web);
					
					Head.AddMetaTag("description", Globals.HtmlEncode(Formatter.RemoveHtml(excerpt,250).Trim()),Context);


					if(this.CurrentGallery.EnableRss)
					{
						string commentRssUrl = GalleryUrls.Instance().CommentRss(this.CurrentGallery.ApplicationKey, DataSource.PostID);
						bool isAvailableToPublic = Permissions.ValidatePermissions(CurrentGallery, Permission.View, Users.GetAnonymousUser(true));
						if (isAvailableToPublic)
							Head.AddRssAutoDiscovery(DataSource.Subject + " Comment RSS", Globals.FullPath(commentRssUrl), Context);
						else if (cSContext.SiteSettings.EnableSecureSyndication)
							Head.AddRssAutoDiscovery(DataSource.Subject + " Comment RSS", Globals.FullPath(SiteUrls.FormatUrlWithUserNameToken(commentRssUrl, cSContext.User, true)), Context);
					}

					// Set visibility of statistic properties based on what is enabled/disabled for the gallery
					if(this.TotalComments != null)
						TotalComments.Visible = DataSource.EnableComments;


					// Statistic properties
					if(PostAuthor != null)
					{
						User author = Users.GetUser(DataSource.AuthorID, false);
						if(author.IsAnonymous)
							PostAuthor.Text = DataSource.Username;
						else
							PostAuthor.Text = "<a href='" + Globals.GetSiteUrls().UserProfile(author.UserID) + "'>" + author.DisplayName + "</a>";
					}
					if(this.ViewCount != null)
						ViewCount.Text = DataSource.Views.ToString();
					if(this.TotalComments != null)
						TotalComments.Text = DataSource.Replies.ToString();

					// Links from this page
					if(this.detailsImage != null)
						detailsImage.NavigateUrl = GalleryUrls.Instance().PictureUrl(DataSource);
					if(this.OriginalLink != null)
						OriginalLink.NavigateUrl = detailsImage.NavigateUrl;

					// Resource text
					if(this.OriginalLink != null)
						OriginalLink.Text = ResourceManager.GetString( "Gallery_PictureDetails_OriginalPicture" );


					if(ViewPictureLink != null)
					{
						ViewPictureLink.Text = ResourceManager.GetString("Gallery_ExifListing_Back" );

						if(cSContext.CategoryID > 0)
							ViewPictureLink.NavigateUrl = GalleryUrls.Instance().ViewPicture(DataSource.Section.ApplicationKey, cSContext.CategoryID, DataSource) ;
						else
							ViewPictureLink.NavigateUrl = GalleryUrls.Instance().ViewPicture(DataSource.Section.ApplicationKey, DataSource) ;
					}

					if (InlineTagEditor != null)
					{
						InlineTagEditor.PostID = DataSource.PostID;
						InlineTagEditor.SelectedTags = DataSource.Categories;
					}
			
					// Enable Order Prints
					if(OrderLink != null)
					{
						if(CurrentGallery.EnableOrderPrints)
						{
							OrderLink.Text = ResourceManager.GetString( "Gallery_PictureDetails_OrderPrints" );
							OrderLink.NavigateUrl = "javascript:void(0);";
							OrderLink.Attributes.Add("onclick", "javascript:window.open('" + GalleryUrls.Instance().ViewOrderPrints(CurrentGallery.ApplicationKey, DataSource.PostID, DataSource.Attachment.Width, DataSource.Attachment.Height, 140, 150) + "', '_blank', '');");
							OrderLink.Visible = true;
						}
						else
							OrderLink.Visible = false;
					}

					if(tb != null)
					{
						tb.Title = DataSource.Subject;
						tb.PermaLink = GalleryUrls.Instance().ViewPicture(DataSource.Section.ApplicationKey, DataSource);
						tb.PingUrl = GalleryUrls.Instance().TrackbackPingUrl(DataSource.PostID);
	
						if(!controlHasBound)
							this.Controls.Add(tb);
					}


					try
					{
						Referral r = new Referral();
						r.SettingsID = cSContext.SiteSettings.SettingsID;
						r.SectionID = DataSource.SectionID;
						r.PostID = DataSource.PostID;
						Referrals.AddToQueue(Context,CurrentGallery.ReferralFilter,r);
					}
					catch{}

					controlHasBound = true;
				}
			}

		}

        [AjaxMethod(IncludeControlValuesWithCallBack=false)]
        public void UpdatePictureTitle(string title)
        {
            if(Permissions.ValidatePermissions(this.CurrentGallery,Permission.Post,this.CurrentUser))
            {

                GalleryPost gp = GalleryPosts.GetPicture(cSContext.PostID,true);
                if(gp != null)
                {
                    gp.Subject = title;
                    GalleryPosts.UpdatePicture(gp);
                }
            }

        }

        [AjaxMethod(IncludeControlValuesWithCallBack=false)]
        public void UpdatePictureDescription(string desc)
        {
            if(Permissions.ValidatePermissions(this.CurrentGallery,Permission.Post,this.CurrentUser))
            {

                GalleryPost gp = GalleryPosts.GetPicture(cSContext.PostID,true);
                if(gp != null)
                {
                    gp.Body = desc;
                    gp.FormattedBody = desc;
                    GalleryPosts.UpdatePicture(gp);
                }
            }

        }
	
		protected bool CanUserView(GalleryPost post)
		{
			//Always validate the sectionid
			if(post.SectionID != CurrentGallery.SectionID)
				Globals.Return404(Context);

			if(!Permissions.ValidatePermissions(CurrentGallery,Permission.Post,this.CurrentUser))
			{
				if(!post.IsPostEnabled)
					Globals.Return404(Context);
			}

			return true;
	
		}
	}
}

