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

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

namespace CommunityServer.Discussions.Controls
{
	public class GroupCollapsableArea : CollapsableArea
	{
		Group _group = null;
		public virtual Group Group
		{
			get
			{
				return _group;
			}
			set
			{
				_group = value;
				if (_group != null)
					this.Parameter = _group.GroupID.ToString();
			}
		}

		protected override void OnInit(EventArgs e) 
		{
			CSContext cntx = CSContext.Current;
			if (cntx.User.IsAnonymous || this.Page.Request.QueryString["personalize"] == "true" || cntx.GroupID > -1)
				this.EnableCollapseExpand = false;		

			this.Collapse += new System.EventHandler(this.OnGroupCollapse);
			this.Expand += new System.EventHandler(this.OnGroupExpand);

			base.OnInit(e);
		}

		protected override void OnPreRender(System.EventArgs e)
		{
			User user = CSContext.Current.User;

			if (this.EnableCollapseExpand)
			{
				this.IsExpanded = true;
				foreach(int i in user.MinimizedGroups)
				{
					if(i == Group.GroupID)
					{
						this.IsExpanded = false;
						break;
					}
				}
			}

			base.OnPreRender(e);
		}

		public void OnGroupCollapse(object sender, System.EventArgs e)
		{
			User user = Users.GetUser(CSContext.Current.User.UserID, false, false);

			if(!user.IsAnonymous)
			{
				user.AddMinimizedGroup(int.Parse(this.Parameter));
				Users.UpdateUser(user);
			}
		}

		public void OnGroupExpand(object sender, System.EventArgs e)
		{
			User user = Users.GetUser(CSContext.Current.User.UserID, false, false);
	
			if(!user.IsAnonymous)
			{
				user.RemoveMinimizedGroup(int.Parse(this.Parameter));
				Users.UpdateUser(user);
			}
		}
	}
}
