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

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

namespace CommunityServer.Discussions.Controls
{
	/// <summary>
	/// Summary description for PostThreadedView.
	/// </summary>
	public class PostSelectedView : Control
	{
	    CSContext csContext;


		#region Control Event Handlers

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

			this.csContext = CSContext.Current;
			
			EnsureChildControls();
		}

		protected override void CreateChildControls()
		{
			base.CreateChildControls();
		
			PostViewType view;
			if (!Globals.IsNullorEmpty(Page.Request.QueryString["View"]))
			{
				try
				{
					view = (PostViewType) Enum.Parse(typeof(PostViewType), Page.Request.QueryString["View"], false);
					UpdateCookie(view);
				}
				catch
				{
					view = GetUserPostViewType();
				}
			}
			else
				view = GetUserPostViewType();

			switch (view)
			{
				case PostViewType.Flat:
					PostFlatView flatView = new PostFlatView();
					flatView.EnableViewState = false;
					this.Controls.Add(flatView);

					break;

				case PostViewType.Threaded:
					PostThreadedView threadView = new PostThreadedView();
					threadView.EnableViewState = false;
					this.Controls.Add(threadView);

					break;
			}
		}

		#region Helper Methods

		public void UpdateCookie(PostViewType view)
		{
			string cookieName = string.Format("{0}_{1}_{2}", csContext.SettingsID, csContext.User.Username, "PostViewType");
		    HttpCookie cookie = Page.Request.Cookies[cookieName];
			if(cookie == null)
				cookie = new HttpCookie(cookieName); 

			if (view == csContext.User.PostViewType)
				cookie.Values.Remove("P" + csContext.PostID.ToString());
			else
				cookie.Values["P" + csContext.PostID.ToString()] = ((int) view).ToString();

			cookie.Expires = DateTime.Now.AddDays(30);
			Page.Response.Cookies.Add(cookie);
		}

		public PostViewType GetUserPostViewType()
		{
			string cookieName = string.Format("{0}_{1}_{2}", csContext.SettingsID, csContext.User.Username, "PostViewType");
			HttpCookie cookie = Page.Request.Cookies[cookieName];
			if(cookie != null && cookie.Values["P" + csContext.PostID.ToString()] != null)
				return (PostViewType) int.Parse(cookie.Values["P" + csContext.PostID.ToString()]);
			else
				return csContext.User.PostViewType;
		}

		#endregion

		#endregion
	}
}