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

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

namespace CommunityServer.Files.Controls
{
	/// <summary>
	/// Summary description for FolderGroupListing.
	/// </summary>
	public class FolderGroupListing : FileGalleryTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;

		#region Child Controls

		private Literal groupName;
		private Repeater folders;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			groupName = (Literal)FindControl("GroupName");
			folders = (Repeater)FindControl("Folders");

			if (folders != null)
				folders.ItemDataBound += new RepeaterItemEventHandler(folders_ItemDataBound);
		}

		#endregion

		int _groupID = -2;
		public int GroupID
		{
			get 
			{
				if (_groupID == -2)
					_groupID = csContext.GroupID;
				
				return _groupID;
			}
			set
			{
				_groupID = value;
			}
		}

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

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

			if (folders != null)
			{
				folders.DataSource = Folders.GetFoldersByGroupID(GroupID, false, true, false);
				folders.DataBind();
			}

			if (groupName != null)
				groupName.Text = Folders.GetFolderGroup(GroupID, true, false).Name;
		}

		private void folders_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			Folder folder = e.Item.DataItem as Folder;

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

					HyperLink name = e.Item.FindControl( "Name" ) as HyperLink;
					IText files = TextControlHelper.Create(e.Item.FindControl("Files"));
					IText comments = TextControlHelper.Create(e.Item.FindControl("Comments"));
					IText description = TextControlHelper.Create(e.Item.FindControl("Description"));

					if(name != null)
					{
						name.Text = folder.Name;
						name.NavigateUrl = FileGalleryUrls.Instance().ViewFolder(folder.ApplicationKey);
					}

					if (files != null)
						files.Text = folder.TotalThreads.ToString();

					if (comments != null)
						comments.Text = (folder.TotalPosts - folder.TotalThreads).ToString();

					if (description != null)
						description.Text = folder.Description;

					break;
			}
		}
	}
}
