// Personal Webpage Engine
// Copyright(c) 2008 Mihail Kochanov
// You can contact me at StilgarAD@yahoo.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//------------------------------------------------------------------------------
//
// Personal Web Page Engine
//
//------------------------------------------------------------------------------

using System;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace WebControls
{
    public partial class NewsItemControl : System.Web.UI.UserControl
    {

        #region Properties

        public NewsItem NewsItem { get; set; }
        public BlogNETDataContext DataContext { get; set; }

        [DefaultValue(true)]
        public bool ShowCommentsLink { get; set; }

        [DefaultValue(false)]
        public bool ShowFullText { get; set; }

        #endregion

        #region PageEvents

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Roles.IsUserInRole(Constants.Roles.Admin))
            {
                pnlAdministration.Visible = true;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            lbPostAuthor.Text = NewsItem.AuthorUsername;
            lbPostDate.Text = NewsItem.PostDate.ToTimeAdjustedString();
            ltPostTitle.Text = NewsItem.Title;

            hlEdit.NavigateUrl = "~/Admin/EditNewsItem.aspx?" + Constants.QueryString.NewsItemID + "=" + NewsItem.NewsItemID;

            if (ShowFullText)
            {
                ltPostText.Text = String.IsNullOrEmpty(NewsItem.Text) ? NewsItem.ShortText : NewsItem.Text;
            }
            else
            {
                ltPostText.Text = NewsItem.ShortText;
            }

            //add tags
            foreach (Tag t in NewsItem.Tags)
            {
                phTags.Controls.Add(new HyperLink { Text = t.TagValue, NavigateUrl = "~/Main.aspx?" + Constants.QueryString.Tag + "=" + t.TagValue });
                phTags.Controls.Add(new Literal { Text = "&nbsp;" });
            }

            if (ShowCommentsLink)
            {
                hlComments.Visible = true;
                //check if news has full text
                //add comments number
                hlComments.NavigateUrl = "~/ViewNewsItem.aspx?" + Constants.QueryString.NewsItemID + "=" + NewsItem.NewsItemID;
                hlComments.Text = "View "
                    + (!String.IsNullOrEmpty(NewsItem.Text) ? "full text and " : "") //add text to indicate news item has full text
                    + "comments(" + NewsItem.CommentsCount + ")";
            }
            else
            {
                hlComments.Visible = false;
            }

            //check if news has been edited
            if (NewsItem.LastEditedDate != null)
            {
                //add last editor and last edited date
                lastEdit.Visible = true;
                lbLastEditDate.Text = NewsItem.LastEditedDate.Value.ToTimeAdjustedString();
                lbLastEditor.Text = NewsItem.LastEditedBy;
            }

            if (NewsItem.Image != null)
            {
                pnlImage.Visible = true;
                //string guid = Guid.NewGuid().ToString();
                imgNewsItem.ImageUrl = "~/HttpHandlers/ImageHandler.ashx?" + Constants.QueryString.NewsItemImageID + "=" + Session.SessionID + NewsItem.NewsItemID;
                //why we need to decode here is beyond me
                //maybe the AlternateText property does encode again
                imgNewsItem.AlternateText = Server.HtmlDecode(NewsItem.Title);

                //save the image in Cache for use by the HttpHandler
                //the HttpHandler is responsible for removing the image from Cache
                Cache.Insert(
                    Constants.Cache.NewsItemImage + Session.SessionID + NewsItem.NewsItemID,
                    NewsItem.Image.ToArray(),
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    new TimeSpan(0, 1, 0),
                    System.Web.Caching.CacheItemPriority.AboveNormal,
                    null);
            }

        }

        #endregion

        #region ControlEvents

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(DeleteCommandName))
            {
                CommandEventArgs args = new CommandEventArgs(this.DeleteCommandName, this.DeleteCommandArgument);
                OnDeleteCommand(args);
            }
            else
            {
                DataContext.NewsItems.DeleteOnSubmit(NewsItem);
                DataContext.SubmitChanges();

                Cache.Remove(Constants.Cache.LatestComments);
                Cache.Remove(Constants.Cache.Tags);

                //delete button from ViewNewsItem.aspx redirects to Main.aspx because NewsItem has been removed
                Response.Redirect("~/Main.aspx");
            }
        }

        #endregion

        #region DeleteCommand

        private string deleteCommandName;

        [DefaultValue("")]
        public string DeleteCommandName
        {
            get
            {
                return deleteCommandName == null ? String.Empty : deleteCommandName;
            }
            set
            {
                deleteCommandName = value;
            }
        }

        public string deleteCommandArgument;

        [DefaultValue("")]
        public string DeleteCommandArgument
        {
            get
            {
                return deleteCommandArgument == null ? String.Empty : deleteCommandArgument;
            }
            set
            {
                deleteCommandArgument = value;
            }
        }

        protected static readonly object EventCommand = new object();

        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommand, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommand, value);
            }
        }

        protected virtual void OnDeleteCommand(CommandEventArgs ce)
        {
            CommandEventHandler ceh = this.Events[EventCommand] as CommandEventHandler;
            if (ceh != null)
            {
                ceh(this, ce);
            }

            //This is the trick to cause Command event to bubble up
            base.RaiseBubbleEvent(this, ce);
        }

        #endregion

    }
}