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

using System;
using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CPResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;

namespace CommunityServer.ControlPanel.Blogs
{

    public class CommentActionsPopup : ClientPopulatedPopupMenu
    {
        protected override void OnInit(EventArgs e)
        {
            //this.ResourceName = "ContactPopupMenu_Text";
            this.Text = "Actions";
            base.OnInit (e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            this.Parameters = new string[1];
            this.Parameters[0] = this.PostID.ToString();
            base.OnPreRender (e);
        }


        protected override System.Collections.ArrayList ClientMenuItemFormats
        {
            get
            {
                ArrayList list = new ArrayList();
                ClientMenuItemFormat format = null;

                format = new ClientMenuItemFormat();
                format.NavigateUrl = ViewUrl;
                format.Text = "View";
                format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
                list.Add(format);

                //<a href="javascript:Telligent_Modal.Open('commenteditor.aspx?cid=<%# DataBinder.Eval(Container.DataItem,"PostID") %>', 625, 475, refreshCallback);">

                format = new ClientMenuItemFormat();
                //format.NavigateUrl = ApproveUrl;
                format.Text = "Edit";
                format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
                format.ClientSideCommand = ModalHelper.BuildHandler(this.Page, "commenteditor.aspx?cid={0}",625,475,"refreshCallback");
                list.Add(format);


                format = new ClientMenuItemFormat();
                format.NavigateUrl = ApproveUrl;
                format.Text = "Publish";
                format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
                list.Add(format);

                format = new ClientMenuItemFormat();
                format.NavigateUrl = ModerateUrl;
                format.Text = "Unpublish";
                format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
                list.Add(format);

                format = new ClientMenuItemFormat();
                //format.NavigateUrl = DeleteUrl;
                format.Text = "Delete";
                format.ClientSideDisplayFunction = "new Function('parms', 'return true;')";
                //format.ClientSideCommand = "if(confirm('" + CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Blog_Comments_Delete_Warning") +"')){window.location = " + this.DeleteUrl + ";}";
                format.ClientSideCommand =   "if(confirm('"+ CommunityServer.ControlPanel.Components.ResourceManager.GetString("CP_Blog_Comments_Delete_Warning") + "'  )){window.location = '" + this.DeleteUrl + "';}";
                //format.ClientSideCommand = "if(confirm('Yes or No')){alert('Yes');};";
                list.Add(format);
                return list;
            }
        }
   
        public string DeleteUrl;
        public string ApproveUrl;
        public string ViewUrl;
        public string ModerateUrl;
        public int PostID;
    }

	/// <summary>
	/// Summary description for PostEditorPage.
	/// </summary>
	public class CommentsPage : BaseBlogPage
	{
		protected CommunityServer.ControlPanel.Controls.ControlPanelSelectedNavigation SelectedNavigation1;
		protected CommunityServer.Controls.MPContent DescriptionRegion;
		protected CommunityServer.Controls.MPContent TaskRegion;
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol1;
		protected CommunityServer.ControlPanel.Controls.ResourceControl Resourcecontrol2;
		protected CommunityServer.Controls.MPContainer MPContainer;
        protected Repeater theComments;

        protected IButton ActionButton;
        protected HelpIcon Helpicon1;
        protected ResourceControl FeedbackFilterLabel;
        protected DropDownList filterPost;
        protected DropDownList filterBlogPostType;
        protected DropDownList filterPublished;
        protected IButton FilterButton;
        protected Modal Modal1;
        protected DropDownList ActionList;
		protected DropDownList SpamFilter;
        protected IPagedControl csPager;

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

        [AjaxMethod(IncludeControlValuesWithCallBack=false)]
        public void Toggle(int postid)
        {
            WeblogPost post = WeblogPosts.GetPost(postid,false,false,false);
            post.IsApproved = !post.IsApproved;
            if(post.IsApproved)
            {
                if (((post.PostStatus & PostStatus.Spam) == PostStatus.Spam) || ((post.PostStatus & PostStatus.LikelySpam) == PostStatus.LikelySpam))
                {
					post.PostStatus &= ~PostStatus.Spam;
					post.PostStatus &= ~PostStatus.LikelySpam;
                    post.PostStatus |= PostStatus.Ham;
                    post.SpamScore = 0;
                }
            }
            WeblogPosts.Update(post);
        }

        /// <summary>
        /// The users prefered Grid Page Size, Will return default values before the OnLoad event
        /// Due to dependancy on CSConect.Current.User
        /// </summary>
        public int DefaultPageSize
        {
            get
            {
                    return Globals.SafeInt(this.CurrentUser.GetExtendedAttribute("CPPageSize"),10);
            }
        }

		private void Page_Load(object sender, EventArgs e)
		{
            AjaxManager.Register(this,"Comments");

            if(!this.IsCallBack)
            {
            theComments.ItemCreated +=new RepeaterItemEventHandler(theComments_ItemCreated);
            JavaScript.RegisterRefresh(this);
            //FilterButton.Click +=new EventHandler(FilterButton_Click);
            FilterButton.Attributes.Add("onclick", "redirectUrl();");
                if(!IsPostBack)
                {

                    BindFilters();

                    string action = Request.QueryString["action"];
                    if(action != null)
                        HandleActions(action);

                    CSContext context = CSContext.Current;

                    int parentid = context.GetIntFromQueryString("pid",-1);
                    int bpt = context.GetIntFromQueryString("bpt",-1);
                    int sf = context.GetIntFromQueryString("spam", 0); 

                    BlogThreadQuery query = new BlogThreadQuery();
                    query.SectionID = CurrentWeblog.SectionID;
			
                    // Show posts for an inactive section if the user is an admin
                    query.RequireSectionIsActive = !context.User.IsAdministrator;

                    query.PageSize = this.DefaultPageSize;
                    query.PageIndex = context.PageIndex;
                    query.ParentID = parentid;

                    if(bpt == -1)
                        query.BlogPostType = BlogPostType.Comment | BlogPostType.PersonalComment | BlogPostType.Trackback;
                    else
                    {
                        query.BlogPostType = (BlogPostType)bpt;
                    }
            	
                    CommunityServer.Spam.SpamConfiguration spamConfig = CommunityServer.Spam.SpamConfiguration.Instance();
                    switch(sf)
                    {
                        case 0: 
                            query.MaximumSpamScore = CurrentWeblog.SpamAutoModerateScore > 0
                                ? CurrentWeblog.SpamAutoModerateScore
                                : spamConfig.AutoModerateScore;
                            break;
            			
                        case 1: 
                            query.MaximumSpamScore = CurrentWeblog.SpamAutoDeleteScore > 0
                                ? CurrentWeblog.SpamAutoDeleteScore
                                : spamConfig.AutoDeleteScore;
            			
                            query.MinimumSpamScore = CurrentWeblog.SpamAutoModerateScore > 0
                                ? CurrentWeblog.SpamAutoModerateScore
                                : spamConfig.AutoModerateScore;            			
                            break;            			
            			
                        case 2: 
                            query.MinimumSpamScore = CurrentWeblog.SpamAutoDeleteScore > 0
                                ? CurrentWeblog.SpamAutoDeleteScore
                                : spamConfig.AutoDeleteScore;
                            break;
            		
                    }

                    query.PublishedFilter = (BlogPostPublishedFilter)context.GetIntFromQueryString("ip", (int)BlogPostPublishedFilter.All);

                    query.SortOrder = SortOrder.Descending;

                    int postID = context.GetIntFromQueryString("pid",-1); 
                    if(postID > -1)
                        query.ParentID = postID;

                    ThreadSet ts = WeblogPosts.GetBlogThreads(query, false);

                    theComments.DataSource = ts.Threads;
                    theComments.DataBind();

                    csPager.PageSize = this.DefaultPageSize;
                    csPager.TotalRecords = ts.TotalRecords;
                    csPager.PageIndex = context.PageIndex;
                    //csPager.DataBind();
                }
            }
		}

        private void HandleActions(string action)
        {
            if(action != null && Request.QueryString["postids"] != null)
            {
                action = action.ToLower();
                string[] postids = Request.QueryString["postids"].Split(',');
                if(postids != null && postids.Length > 0)
                {
                    foreach(string sp in postids)
                    {
                        int pid = Globals.SafeInt(sp,-1);
                        if(pid > -1)
                        {
                            WeblogPost post = WeblogPosts.GetPost(pid,false,false,false);    
                            if(post != null && post.IsFeedback && post.SectionID == this.CurrentWeblog.SectionID)
                            {
                                switch(action.ToLower())
                                {
                                    case "approve": 
                                        post.IsApproved = true;


                                        if (((post.PostStatus & PostStatus.Spam) == PostStatus.Spam) || ((post.PostStatus & PostStatus.LikelySpam) == PostStatus.LikelySpam))
                                        {
											post.PostStatus &= ~PostStatus.Spam;
											post.PostStatus &= ~PostStatus.LikelySpam;
                                            post.PostStatus |= PostStatus.Ham;
                                            post.SpamScore = 0;
                                        }
                                        

                                        WeblogPosts.Update(post,CurrentUser.UserID);
                                        break;
                                    case "moderate":
                                        post.IsApproved = false;
                                        WeblogPosts.Update(post,CurrentUser.UserID);
                                        break;
                                    case "delete":
                                        WeblogPosts.Delete(post,CurrentUser.UserID);
                                        break;
                                }
                            }
                            else
                            {
                                EventLogs.Warn(string.Format("User: {0} ({1}) attemped to {2} postid {3} while logged into section {4}", CurrentUser.Username,CurrentUser.UserID,action,pid,this.CurrentWeblog.SectionID),"Invalid Blog Comment Action", 342, CSContext.Current.SettingsID);
                                throw new CSException(CSExceptionType.AccessDenied, "Invalid Blog Comment Action");
                            }
                            
                        }

                    }

                    FilterButton_Click(null,EventArgs.Empty);
                }
            }
        }


        private void BindFilters()
        {

            // Manually populate the DropDownLists
            filterBlogPostType.Items.Add(new ListItem(ResourceManager.GetString("Feedback_SelectAll"), "-1"));
			filterBlogPostType.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_Comment"), Convert.ToString((int)BlogPostType.Comment)));
			filterBlogPostType.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_Trackback"), Convert.ToString((int)BlogPostType.Trackback)));

            filterPublished.Items.Add(new ListItem(ResourceManager.GetString("Feedback_SelectAll"), ((int)BlogPostPublishedFilter.All).ToString()));
            filterPublished.Items.Add(new ListItem(ResourceManager.GetString("Feedback_FilterPublished"), ((int)BlogPostPublishedFilter.Published).ToString()));
            filterPublished.Items.Add(new ListItem(ResourceManager.GetString("Feedback_FilterNotPublished"), ((int)BlogPostPublishedFilter.NotPublished).ToString()));

        	SpamFilter.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_NotSpam"), "0"));
        	SpamFilter.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_PossibleSpam"), "1"));
        	SpamFilter.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_Spam"), "2"));
        	SpamFilter.Items.Add(new ListItem(CPResourceManager.GetString("CP_Blog_Comments_Ignore"), "-1"));
       	
        	
            // Retrieve list of recent blog posts
            BlogThreadQuery query = new BlogThreadQuery();
            query.SectionID = this.CurrentWeblog.SectionID;
            query.BlogPostType = BlogPostType.Post | BlogPostType.Article;
            query.BlogThreadType = BlogThreadType.Recent;
            query.IncludeCategories = false;
            query.PublishedFilter = BlogPostPublishedFilter.All;
            query.PageSize = 20;
            query.SortOrder = SortOrder.Descending;
            query.SortBy = BlogThreadSortBy.MostRecent;
            ThreadSet threads = WeblogPosts.GetBlogThreads(query,false);

            // Insert default "All" item
            filterPost.Items.Add(new ListItem(ResourceManager.GetString("Feedback_FilterAll"), "-1"));

            foreach (WeblogPost post in threads.Threads)
            {
                filterPost.Items.Add(new ListItem(Globals.HtmlDecode(post.Subject), Convert.ToString(post.PostID)));
            }

            // Check if preselected values of the filter DropDownLists were passed in the URL
            CSContext context = CSContext.Current;
            ListItem li = null;

            int pid = context.GetIntFromQueryString("pid",-1);

            if(pid > -1)
            {
                li = filterPost.Items.FindByValue(pid.ToString());
                if(li != null)
                {
                    li.Selected = true;
                
                }
            }

            li = filterBlogPostType.Items.FindByValue(context.GetIntFromQueryString("bpt",(int)(BlogPostType.Comment | BlogPostType.PersonalComment | BlogPostType.Trackback)).ToString());

            if(li != null)
                li.Selected = true;
            

            li = filterPublished.Items.FindByValue(context.GetIntFromQueryString("ip", (int)BlogPostPublishedFilter.All).ToString());
            if(li != null)
                li.Selected = true;
            
        	
        	li = SpamFilter.Items.FindByValue(context.GetIntFromQueryString("spam", 0).ToString());
        	if(li != null)
        		li.Selected = true;
        }

        private void FilterButton_Click(object sender, EventArgs e)
        {
            Response.Redirect(GetFilteredUrl());
            Response.End();
        }

        private string GetFilteredUrl()
        {
            string url  = "{0}?pid={1}&ip={2}&bpt={3}&spam={4}";
            url = string.Format(url,Request.Path,filterPost.SelectedValue,filterPublished.SelectedValue,filterBlogPostType.SelectedValue,SpamFilter.SelectedValue);            
            return url;
        }

        protected string GetActionUrl(string action, object PostID)
        {
            return GetFilteredUrl() + "&action="+ action + "&postids=" + PostID.ToString();
        }

        private void theComments_ItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                WeblogPost post = e.Item.DataItem as WeblogPost;
                CommentActionsPopup cap = e.Item.FindControl("actionMenu") as CommentActionsPopup;
                if(post != null && cap != null)
                {
                    cap.PostID = post.PostID;
                    cap.ApproveUrl = GetActionUrl("approve","{0}");
                    cap.ViewUrl = post.ViewPostURL;
                    cap.DeleteUrl = GetActionUrl("delete", "{0}");
                    cap.ModerateUrl = GetActionUrl("moderate","{0}");
                }
                
            }
        }
    }
}
