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

using System;
using System.Collections;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Files.Components;

namespace CommunityServer.Files.Controls
{

	public class CategoryListing : FileGalleryTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;

		#region Private Members

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

		#endregion

		#region Child Controls

		private RepeaterPlusNone Categories;
		private PagingControl pagination;
		private HtmlTableCell footerRow;

		#endregion

		#region Public Properties

		[DefaultValue( "" )]
		public virtual string ApplicationKey
		{
			get
			{
				Object state = ViewState["ApplicationKey"];
				if(state != null)
					return (string)state;
				return "";
			}
			set { ViewState["ApplicationKey"] = value; }
		}

		[DefaultValue( 0 )]
		public virtual Int32 CategoryID
		{
			get
			{
				Object state = ViewState["CategoryID"];
				if(state != null)
					return (Int32)state;
				return 0;
			}
			set
			{ ViewState["CategoryID"] = value; }
		}

		[DefaultValue( 1 )]
		public virtual Int32 CurrentPage
		{
			get
			{
				Object state = ViewState["CurrentPage"];
				if(state != null)
					return (Int32)state;
				return 1;
			}
			set
			{ ViewState["CurrentPage"] = value; }
		}

		[DefaultValue( 2 )]
		public virtual Int32 Columns
		{
			get
			{
				Object state = ViewState["Columns"];
				if(state != null)
					return (Int32)state;
				return 2;
			}
			set
			{ ViewState["Columns"] = value; }
		}

		[DefaultValue( 3 )]
		public virtual Int32 Rows
		{
			get
			{
				Object state = ViewState["Rows"];
				if(state != null)
					return (Int32)state;
				return 3;
			}
			set
			{ ViewState["Rows"] = value; }
		}

		[DefaultValue( 0 )]
		protected virtual Int32 TotalCategories
		{
			get
			{
				Object state = ViewState["TotalCategories"];
				if(state != null)
					return (Int32)state;
				return 0;
			}
			set
			{ ViewState["TotalCategories"] = value; }
		}

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Categories = (RepeaterPlusNone)FindControl( "Categories" );
			pagination = (PagingControl)FindControl( "Pagination" );
			footerRow = FindControl( "FooterRow" ) as HtmlTableCell;
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			Categories.ItemDataBound += new RepeaterItemEventHandler(Categories_ItemDataBound);
			Categories.NoneItemsDataBound += new RepeaterItemEventHandler(Categories_NoneItemsDataBound);
		}

		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			ApplicationKey = csContext.ApplicationKey;
			CategoryID = (csContext.CategoryID != -1) ? csContext.CategoryID : 0;

			// Get the default columns and rows
			Folder folder = Folders.GetFolder(ApplicationKey);
			Columns = 1;
			Rows = 10;

			// Grab the page number
			if(this.Page.Request.QueryString["cpage"] != null)
				CurrentPage = int.Parse(this.Page.Request.QueryString["cpage"]);
		}

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

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

		private void BindCategories()
		{
			ArrayList categories = PostCategories.GetCategories(Folders.GetFolderID(ApplicationKey), CategoryID);

			// If no categories, hide it and return
			if(categories.Count == 0)
			{
				this.Visible = false;
				return;
			}

			// Calculate pagination
			TotalCategories = categories.Count;
			int pageCount = categories.Count;
			pageCount -= (CurrentPage-1)*Columns*Rows;
			if(pageCount > (Columns*Rows))
				pageCount = Columns*Rows;

			// Setup the pagination
			pagination.CurrentPage = CurrentPage;
			pagination.TotalPages = (int)Math.Ceiling( (double)TotalCategories / (double)(Columns*Rows) );
			pagination.PrefixText = "page";
			pagination.QueryName = "cpage";
			pagination.NavigateUrl = Page.Request.RawUrl;
			pagination.DataBind();

			// Grab the items for the current page
			PostCategory[] pageItems = new PostCategory[pageCount];
			categories.CopyTo((CurrentPage-1)*Columns*Rows, pageItems, 0, pageCount);

			// Set the datasource and bind
			Categories.DataSource = pageItems;
			Categories.DataBind();

			// Set the footer row colspan
			if(footerRow != null)
				footerRow.ColSpan = totalColumns;
		}

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

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

					HyperLink NameLink = (HyperLink)e.Item.FindControl( "Name" );
					IText DescLabel = TextControlHelper.Create(e.Item.FindControl( "Description" ));
					IText DateChangedLabel = TextControlHelper.Create(e.Item.FindControl( "DateChanged" ));
					IText TotalPicturesLabel = TextControlHelper.Create(e.Item.FindControl( "TotalPictures" ));

					if (NameLink != null)
					{
						NameLink.Text = dataItem.Name;
						NameLink.NavigateUrl = FileGalleryUrls.Instance().ViewCategory(ApplicationKey, dataItem.CategoryID);
					}

					if (TotalPicturesLabel != null)
						TotalPicturesLabel.Text = dataItem.TotalSubThreads.ToString();

					if (DescLabel != null)
					{
						if(dataItem.Description.Length > 50)
							DescLabel.Text = dataItem.Description.Substring(0, 50) + "...";
						else
							DescLabel.Text = dataItem.Description;
						if(DescLabel.Text != string.Empty)
							DescLabel.Text += "<br/>";
					}

					// If there are no posts, the MostRecentPostDate field has a funky value... lets show when the album was created
					if (DateChangedLabel != null)
					{
						if(dataItem.MostRecentSubPostDate <= SqlDateTime.MinValue.Value)
						{
							DateChangedLabel.Visible = false;
							e.Item.FindControl( "ChangedTitle" ).Visible = false;
						}
						else
						{
							User user = csContext.User;
							DateTime changedDate = dataItem.MostRecentSubPostDate;
							string dateFormat;

							if(!user.IsAnonymous)
							{
								changedDate = user.GetTimezone(changedDate);
								dateFormat = user.Profile.DateFormat;
							}
							else
								dateFormat = csContext.SiteSettings.DateFormat;

							DateChangedLabel.Text = changedDate.ToString(dateFormat) + " " + changedDate.ToString(csContext.SiteSettings.TimeFormat);
						}
					}

					// 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" );
						if (BeginRowLabel != null)
							BeginRowLabel.Text = "<tr>";
					}
					columnCount++;
					if(!totalColumnsFound)
						totalColumns++;

					// End a column, if necessary
					if((columnCount == Columns) || ((rowCount*Columns+columnCount) == TotalCategories))
					{
						Literal EndRowLabel = (Literal)e.Item.FindControl( "EndRow" );
						if (EndRowLabel != null)
							EndRowLabel.Text = "</tr>";

						columnCount = 0;
						totalColumnsFound = true;
						rowCount++;
					}

					break;
			}
		}

		private void Categories_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{
			IText NoRecordsLabel = TextControlHelper.Create(e.Item.FindControl( "NoRecords" ));
			if (NoRecordsLabel != null)
				NoRecordsLabel.Text = FileGalleryResourceManager.GetString( "NoRecords" );
		}
	}
}
