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

using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using Content = CommunityServer.Components.Content;

namespace CommunityServer.Controls
{
	/// <summary>
	/// A ContentArticle loads content from the database 
	/// </summary>
	public class ContentArticle: TemplatedWebControl
	{
		private CommunityServer.Components.Content _content = null;
		private Panel _adminpanel;
		private HyperLink _editlink;
		private IText _literal, _title, _title2;
		private string _name = null;
		private int _id = 0;

		public ContentArticle()
		{
		}

		#region overridden methods
        protected virtual bool CanUserEdit()
        {
            return CSContext.Current.User.IsAdministrator;
        }

		protected override void AttachChildControls()
		{
			_editlink = (HyperLink)FindControl("editlink");
			_adminpanel = (Panel)FindControl("adminpanel");
			_literal = FindText("content");
			_title = FindText("title");
			_title2 = FindText("title2");
		}

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

			EnsureChildControls();

			if (!Page.IsPostBack)
			{
				if ((_adminpanel.Visible = CanUserEdit()) == true)
				{
					if (_title != null)
						_title.Text = Content.Title;

					if (_editlink != null)
						_editlink.NavigateUrl = Contents.EditArticleUrl(Content.ID);
				}

				if (_title2 != null)
				{
					if (!Globals.IsNullorEmpty(Content.Title))
						_title2.Text = Content.Title;
					else
						_title2.Visible = false;
				}


				_literal.Text = Content.RenderedBody(PostTarget.Web);
			}

		}
		#endregion

		#region Properties
		private Content Content
		{
			get 
			{
				if (_content == null)
				{
					if (ContentID == 0)
						_content = Contents.GetContent(ContentName);
					else
						_content = Contents.GetContent(ContentID,true);

                    if(_content == null)
                        _content = new Content();
				}

				return _content;
			}
		}

		/// <summary>
		///  the content to display from database, by name
		/// </summary>
		public string ContentName
		{
			get {return _name;}
			set {_name = value;}
		}

		/// <summary>
		///  the content to display from database, by id
		/// </summary>
		public int ContentID
		{
			get {return _id;}
			set {_id = value;}
		}

		/// <summary>
		/// take content ID/name from querystring if true
		/// </summary>
		public bool FromQueryString
		{
			set 
			{
				if (value == true)
				{
					CSContext cntx = CSContext.Current;
					ContentID = Globals.SafeInt(cntx.QueryString["contentid"], 0);

					if (ContentID == 0)
						ContentName = cntx.QueryString["contentname"];
				}
			}
		}
		#endregion
	}
}
