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

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

namespace CommunityServer.Galleries.Controls
{

	public class PictureListing : GalleryThemedControl
	{
		CSContext csContext = CSContext.Current;

		#region Properties

		string[] _filterTags = null;
		public virtual string[] FilterTags
		{
			get
			{
				if (_filterTags == null)
					return csContext.Tags;
				else
					return _filterTags;
			}
			set
			{
				_filterTags = value;
			}
		}

		public virtual bool LogicallyOrTags
		{
			get
			{
				Object state = ViewState["LogicallyOrTags"];
				if ( state != null ) 
				{
					return (Boolean)state;
				}
				return false;
			}
			set
			{
				ViewState["LogicallyOrTags"] = value;
			}
		}

		public virtual string Tags
		{
			get
			{
				return String.Join(",", FilterTags);
			}
			set
			{
				ArrayList tags = new ArrayList();
				foreach (string tag in value.Split(','))
				{
					if (!Globals.IsNullorEmpty(tag.Trim()))
						tags.Add(tag.Trim());
				}
				FilterTags = (string[]) tags.ToArray(typeof(string));
			}
		}

		#endregion

		#region Private Members

		private int columnCount = 0;
		private int rowCount = 0;
		private int totalColumns = 0;
		private bool totalColumnsFound = false;
		private int totalPictures = 0;

		#endregion

		#region Child Controls

		//private GalleryThreadSortDropDownList PictureSortDDL;
		private RepeaterPlusNone Pictures;
		private RssButton rssButton;
		private HtmlTableCell footerRow;
		private Pager pager;
		private CurrentPage currentPage;
		private int Columns;
		private int Rows;
		private Panel pagerPanel;


		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			//For CS 1.2 we are dropping the option to let the user sort
			//PictureSortDDL = (GalleryThreadSortDropDownList)FindControl( "SortPictures" );
			Pictures = (RepeaterPlusNone)FindControl( "Pictures" );
			rssButton = (RssButton)FindControl( "RssButton" );
			footerRow = FindControl( "FooterRow" ) as HtmlTableCell;
			pager = (Pager) FindControl("Pager");
			currentPage = (CurrentPage) FindControl("CurrentPage");
			pagerPanel = (Panel) FindControl("PagerPanel");
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			Pictures.ItemDataBound += new RepeaterItemEventHandler(Pictures_ItemDataBound);
			Pictures.NoneItemsDataBound += new RepeaterItemEventHandler(Pictures_NoneItemsDataBound);
			
			
			//For CS 1.2 we are dropping the option to let the user sort
			//PictureSortDDL.SelectedIndexChanged += new EventHandler(PictureSortDDL_SelectedIndexChanged);

			//GalleryUserCookie userCookie = new GalleryUserCookie(csContext.Current.User);
			//PictureSortDDL.AutoPostBack = true;
			//PictureSortDDL.SelectedSortByValue = userCookie.ThreadSortBy;
			//PictureSortDDL.SelectedSortOrderValue = userCookie.ThreadSortOrder;

			if (rssButton != null)
			{
				bool isAvailableToPublic = Permissions.ValidatePermissions(CurrentGallery, Permission.View, Users.GetAnonymousUser(true));

				if (CurrentGallery.EnableRss && (isAvailableToPublic || csContext.SiteSettings.EnableSecureSyndication))
				{
					string title = Globals.HtmlEncode(CurrentGallery.Name);
					string rssCat;
					if (csContext.CategoryID == -1)
						rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Pictures, csContext.ApplicationKey));
					else
						rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Pictures, csContext.ApplicationKey, csContext.CategoryID));

					if (isAvailableToPublic)
					{
						rssButton.NavigateUrl = rssCat;
						rssButton.IsSecureFeed = false;
					}
					else
					{
						rssButton.NavigateUrl = SiteUrls.FormatUrlWithUserNameToken(rssCat, csContext.User, false);
						rssButton.IsSecureFeed = true;
					}

					rssButton.ImageUrl = Globals.GetSiteUrls().RssImage(false);
					rssButton.IncludeAutodiscovery = true;
					rssButton.AutoDiscoveryTitle = title;
				}
				else
					rssButton.Visible = false;

			}
			else
			{
				// RssButton control does not exist, so add AutoDiscovery manually
				bool isAvailableToPublic = Permissions.ValidatePermissions(CurrentGallery, Permission.View, Users.GetAnonymousUser(true));
				string title = Globals.HtmlEncode(CurrentGallery.Name);
				string rssCat;
				if (csContext.CategoryID == -1)
					rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Pictures, csContext.ApplicationKey));
				else
					rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Pictures, csContext.ApplicationKey, csContext.CategoryID));

				if (isAvailableToPublic)
					Head.AddRssAutoDiscovery(title, rssCat, Context);
				else if (csContext.SiteSettings.EnableSecureSyndication)
					Head.AddRssAutoDiscovery(title, SiteUrls.FormatUrlWithUserNameToken(rssCat, csContext.User, true), Context);
			}

			
		}


		#endregion

		#region Event Overrides

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			// Set the default columns and rows
			Columns = CurrentGallery.PictureListingColumns;
			Rows = CurrentGallery.PictureListingRows;

		}

		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);
			this.DataBind();
		}
	
		public override void DataBind()
		{
			base.DataBind ();
			BindData();
		}

		#endregion

		private void BindData()
		{
            SetPageTitle(null);
			pager.PageIndex = csContext.GetIntFromQueryString("ppage",1)-1; 

			// Set up the query
			GalleryThreadQuery query = new GalleryThreadQuery();
			query.SectionID = CurrentGallery.SectionID;
			query.CategoryID = csContext.CategoryID;
			query.ApplicationPostType = GalleryPostType.Image;
			query.PageIndex = currentPage.PageIndex = pager.PageIndex;
			query.PageSize = Columns*Rows;
			query.PublishedFilter = GalleryPostPublishedFilter.Published;
			query.IncludePageIndex = true; //by setting this we are caching the results for the pager on the details page

			if (this.FilterTags != null && this.FilterTags.Length > 0)
			{
				query.Tags = this.FilterTags;
				query.LogicallyOrTags = this.LogicallyOrTags;
			}

			//For CS 1.2 we are dropping the option to let the user sort
			//query.SortBy = PictureSortDDL.SelectedSortByValue;
			//query.SortOrder = PictureSortDDL.SelectedSortOrderValue;

			query.SortBy = Galleries.GetGallery(csContext.ApplicationKey).ThreadSortBy;
			query.SortOrder = Galleries.GetGallery(csContext.ApplicationKey).ThreadSortOrder;

			// Set the datasource and bind
			ThreadSet ts = GalleryPosts.GetPictures(query);
			Pictures.DataSource = ts.Threads;
			
			Pictures.DataBind();

			pager.UrlPattern = pager.UrlCleaner(csContext.RawUrl,"ppage"); 
			pager.PageSize = query.PageSize;

			
			pager.TotalRecords = currentPage.TotalRecords = totalPictures = ts.TotalRecords;
			currentPage.TotalPages = pager.CalculateTotalPages();

			if(pagerPanel != null)
			{
				pagerPanel.Visible = (currentPage.TotalPages > 1);
				//pagerPanel.DataBind();
			}
	
			// Set the footer row colspan
			if(footerRow != null)
				footerRow.ColSpan = totalColumns;
		}

		private void Pictures_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			GalleryPost dataItem = e.Item.DataItem as GalleryPost;

			switch( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					HyperLink PictureNameLink = (HyperLink)e.Item.FindControl( "PictureName" );
					Literal TotalViews = (Literal)e.Item.FindControl( "TotalViews");
			
					if(PictureNameLink != null)
					{
						PictureNameLink.Text = dataItem.Subject;
						PictureNameLink.NavigateUrl = GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey, csContext.CategoryID, dataItem);
						PictureNameLink.Font.Bold = true;
					}

					if (TotalViews != null)
						TotalViews.Text = string.Format( ResourceManager.GetString( "Gallery_PictureListing_TotalViews" ), dataItem.Views );

					GalleryImage ThumbImage = (GalleryImage)e.Item.FindControl( "ThumbImage" );
					if(ThumbImage != null)
					{
						ThumbImage.PostID = dataItem.PostID;
						ThumbImage.NavigateUrl = GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey, csContext.CategoryID, dataItem);
						ThumbImage.GalleryPost = dataItem;
						ThumbImage.DataBind();
					}

					GalleryImage ThumbLargeImage = e.Item.FindControl( "ThumbLargeImage" ) as GalleryImage;
					if(ThumbLargeImage != null)
					{
						ThumbLargeImage.PostID = dataItem.PostID;
						ThumbLargeImage.NavigateUrl = GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey, csContext.CategoryID, dataItem);
						ThumbLargeImage.GalleryPost = dataItem;
						ThumbLargeImage.DataBind();
					}

					RatingListing ratingListing = (RatingListing)e.Item.FindControl( "RatingListing" );
					if(ratingListing != null)
					{
						ratingListing.ApplicationKey = CurrentGallery.ApplicationKey;
						ratingListing.PictureID = dataItem.PostID;
						ratingListing.GalleryPost = dataItem;
						ratingListing.DataBind();
					}
					// Set column width
					HtmlTableCell tableColumn = e.Item.FindControl("TableColumn") as HtmlTableCell;
					if(tableColumn != null)
						tableColumn.Width = (100 / Columns).ToString() + "%";

					// Begin a column, if necessary
					if(columnCount == 0)
					{
						Literal BeginRowLabel = (Literal)e.Item.FindControl( "BeginRow" );
						BeginRowLabel.Text = "<tr>";
					}
					columnCount++;
					if(!totalColumnsFound)
						totalColumns++;

					// End a column, if necessary
					if((columnCount == Columns) || ((rowCount*Columns+columnCount) == totalPictures))
					{
						Literal EndRowLabel = (Literal)e.Item.FindControl( "EndRow" );
						EndRowLabel.Text = "</tr>";
						columnCount = 0;
						totalColumnsFound = true;
						rowCount++;
					}

					break;
			}
		}

		
		//For CS 1.2 we are dropping the option to let the user sort
		//private void PictureSortDDL_SelectedIndexChanged(object sender, EventArgs e)
		//{
		//	GalleryUserCookie userCookie = new GalleryUserCookie(csContext.Current.User);
		//	userCookie.ThreadSortBy = PictureSortDDL.SelectedSortByValue;
		//	userCookie.ThreadSortOrder = PictureSortDDL.SelectedSortOrderValue;
		//	BindPictures();
		//}

		private void Pictures_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{
			Literal NoRecordsLabel = (Literal)e.Item.FindControl( "NoRecords" );
			NoRecordsLabel.Text = ResourceManager.GetString( "ForumMembers_NoRecords" );
		}

		
	}
}
