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

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

using CommunityServer.Blogs.Components;
using CommunityServer.Components;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Summary description for WeblogCalendar.
	/// </summary>
	public class WeblogCalendar : WeblogThemedControl
	{
		public WeblogCalendar()
		{
			//
			// TODO: Add constructor logic here
			//
		}

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

			int month = Globals.SafeInt(Context.Request.QueryString["M"],-1);
			int year = Globals.SafeInt(Context.Request.QueryString["Y"],-1);
			int day = Globals.SafeInt(Context.Request.QueryString["D"],-1);

			if(month != -1 && year != -1)
			{
				CurrentDate = new DateTime(year,month,day != -1 ? day : 1);

				//This will force the calendar to be set to the month of the selected post or list
				postCalendar.VisibleDate = CurrentDate;
			}
		}

	
		private ArchiveDataItem DataItem(int day)
		{
			if(days == null)
			{
				days = WeblogPosts.GetPostsByMonth(this.CurrentWeblog.SectionID,CurrentDate);
				postCalendar.VisibleDate = CurrentDate;
			}

			return days[day] as ArchiveDataItem;
		}


		private Calendar postCalendar = null;
		private DateTime CurrentDate = DateTime.Now;
		private Hashtable days = null;

		protected override void AttachChildControls()
		{
			postCalendar = FindControl("PostCalendar") as Calendar;
			postCalendar.DayRender +=new DayRenderEventHandler(postCalendar_DayRender);
			postCalendar.VisibleMonthChanged +=new MonthChangedEventHandler(postCalendar_VisibleMonthChanged);
		}

		private void postCalendar_DayRender(object sender, DayRenderEventArgs e)
		{
			e.Cell.Controls.Clear();
			int day = e.Day.Date.Day;

			ArchiveDataItem item = DataItem(day);
			if(!e.Day.IsOtherMonth && item != null)
			{
				HyperLink hl = new HyperLink();
				hl.NavigateUrl = BlogUrls.Instance().DayPage(this.CurrentWeblog.ApplicationKey,item.Date);
				hl.Text = e.Day.DayNumberText;
				if(item.Count > 1)
				{
					hl.ToolTip = item.Count + " Posts";
				}
				else
				{
					hl.ToolTip = item.Count + " Post";
				}
				e.Cell.Controls.Add(hl);
			}
			else
			{
				e.Cell.Controls.Add(new LiteralControl(e.Day.DayNumberText));
			}

		}

		private void postCalendar_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
		{
			CurrentDate = e.NewDate;
		}
	}
}
