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

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace CommunityServer.Blogs.Controls
{
    /// <summary>
    /// Summary description for CommentForum.
    /// </summary>
    public class CommentForm : WeblogThemedControl
    {
        private TextBox tbTitle;
        private TextBox tbName;
        private TextBox tbComment;
        private TextBox tbUrl;
        private CheckBox chkRemember;
        private IButton btnSubmit;
     
        private PlaceHolder CommentFormWrapper;
        private ResourceControl DisabledMessage;
        
        public CommentForm()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        protected override void AttachChildControls()
        {
            tbTitle = FindControl( "tbTitle" ) as TextBox;
            tbName = FindControl( "tbName" ) as TextBox;
            tbComment = FindControl( "tbComment" ) as TextBox;
            tbUrl = FindControl( "tbUrl" ) as TextBox;
            CommentFormWrapper = FindControl("CommentFormWrapper") as PlaceHolder;
            DisabledMessage = FindControl("DisabledMessage") as ResourceControl;
            chkRemember = FindControl( "chkRemember" ) as CheckBox;
            btnSubmit = FindButton( "btnSubmit" );

            Control cntrl = FindControl("Message");
            if(cntrl != null)
            {
                cntrl.Visible = Context.Request.QueryString["CommentPosted"] != null;
            }



            if(Context.Request.IsAuthenticated)
            {
                tbName.Text = CurrentUser.DisplayName;
                (FindControl("NameTitle") as HtmlGenericControl).Visible = false;
                (FindControl("NameDesc") as HtmlGenericControl).Visible = false;
				tbUrl.Text = CurrentUser.Profile.WebLog;
                if(chkRemember != null)
                    chkRemember.Visible = false;
            }



            btnSubmit.Click +=new EventHandler(btnSubmit_Click);
            CheckCookie();

            btnSubmit.Text = ResourceManager.GetString( "Submit" );
            chkRemember.Text = ResourceManager.GetString( "Weblog_CommentForm_RememberMe" );
        }

        private WeblogPost _dataSource;
        
        /// <summary>
        /// Property DataSource (WeblogEntry)
        /// </summary>
        public WeblogPost DataSource
        {
            get
            {  return this._dataSource; }
            set
            {  this._dataSource = value; }
        }

        public override void DataBind()
        {
            if(this.DataSource == null)
            {
                this.Visible = false;
                return;
            }


            this.EnsureChildControls();

            if(CurrentWeblog.EnableNewComments(DataSource,CurrentUser))
            {
                if(tbTitle != null)
                    tbTitle.Text = "re: " + Globals.HtmlDecode(DataSource.Subject);
            }
            else
            {
                if(CommentFormWrapper == null)
                    this.Visible = false;
                else
                {
					if(DisabledMessage != null)
					{
						DisabledMessage.Visible = true;
						if (CurrentUser.IsAnonymous && !CurrentWeblog.isAnonymousCommentsEnabled(DataSource))
							DisabledMessage.ResourceName = "Weblog_CommentForm_AnonCommentsDisabled";
						else
							DisabledMessage.ResourceName = "Weblog_CommentForm_CommentDisabled";
					}

                    CommentFormWrapper.Visible = false;
                }

            }
        }

        private void CheckCookie()
        {
            if(!Page.IsPostBack)
            {
                HttpCookie user = Context.Request.Cookies["CommentUser"];
                if(user != null)
                {
                    tbName.Text = user.Values["Name"];
                    tbUrl.Text = user.Values["Url"];
                }
            }
        }

        protected string GetTitle()
        {
            if(tbTitle == null || Globals.IsNullorEmpty(tbTitle.Text))
                return "re: " + Globals.HtmlDecode(DataSource.Subject);


            return tbTitle.Text;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if(!Page.IsValid || !CurrentWeblog.EnableNewComments(DataSource, CurrentUser))
                return;

            WeblogPost entry = new WeblogPost();
            entry.TitleUrl = tbUrl.Text;
            entry.Subject = GetTitle();
            entry.Body = tbComment.Text;
            entry.Excerpt = string.Empty;
            entry.IsApproved =  !CurrentWeblog.IsPostModerated(DataSource,CurrentUser);
            entry.ParentID = DataSource.PostID;

            entry.PostType = PostContentType.HTML;
            entry.BlogPostType = BlogPostType.Comment;
            entry.SectionID = DataSource.SectionID;
            entry.UserTime = entry.PostDate = DateTime.Now;

            if (CurrentUser.IsAnonymous)
				entry.SubmittedUserName = tbName.Text;

			// Make sure the URL starts with http://
			if (!entry.TitleUrl.StartsWith("http://") && !entry.TitleUrl.StartsWith("https://"))
				entry.TitleUrl = "http://" + entry.TitleUrl;

			// If it is empty, set it to nothing
			if(entry.TitleUrl == "http://")
				entry.TitleUrl = string.Empty;

			if(chkRemember.Checked)
			{
				HttpCookie userCookie = new HttpCookie( "CommentUser" );
				userCookie.Values.Add("Name", tbName.Text);
				userCookie.Values.Add("Url", tbUrl.Text);
				Context.Response.SetCookie(userCookie);
			}

            int postID = -1;
            BlogPostResults result = WeblogPosts.Add(entry, CurrentUser, out postID);
            if(result == BlogPostResults.Success &&  postID > 0)
                Context.Response.Redirect(BlogUrls.Instance().CommentPosted(DataSource,CurrentWeblog));



        }
    }
}
