using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Spaces;
using System.Xml;
using FreeTextBoxControls;
using Spaces.Blog;
using System.Collections.Generic;
public partial class Admin_EditPost : System.Web.UI.Page
{
    int PostID
    {
        get { return SpacesContext.Current.PostID; }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
       
        AlbumPath.Text = Config.GetConfig().BlogAlbumUrl;
        string postText = Request.Form[PostEditor.ClientID];
        //SetFtb();
        if (!this.IsPostBack)
        {
            BindCategoryList();
            if (PostID > 0)
            {
                BindPost();
            }
        }
        else
        {
            if (postText != "")
            {
                
                    GetPostData();
              
            }
        
        }

    }

    private void GetPostData()
    {
        
        string title = this.blog_title.Value;

        string body = PostEditor.Value;//ftbBody.Text;
        UserConfig uc = Cacher.GetUserConfig(User.Identity.Name);
        DayBook db;
        if (PostID > 0)
        {
            db = Blogs.GetPost(PostID);
            if (db.Account != Account)
            {
                throw new Exception("不是您的日志!");
            }
            db.Tags.Clear();
        }
        else
        {
            db = new DayBook();
            db.Author = uc.Account;
            db.BlogID = uc.BlogID;
            db.DateAdded = DateTime.Now;
            db.Account = uc.Account;//这里做为标记删除cache 用
            db.ParentID = -1;
            db.PostType = PostType.BlogPost;

            db.TitleUrl = string.Empty;
            // 

            db.SourceName = SpacesContext.Current.UserIpAddress;
        }
        db.Text = body;
        db.Title = title;
        db.EnableComment = chkEnableComment.Checked;
        db.Hiding = chkIsHide.Checked;
        db.DateUpdated = DateTime.Now;
        db.Tags = Utils.GetTags(txtTags.Text);
       
        int price = 0;
        db.Price = GetPrice();
        int id = db.ID;
      
        
        if (PostID > 0)//更新文章
        {
           
      
            db.ID = PostID;
            Blogs.UpdatePost(db, GetLinks(uc.BlogID));//加一个Links
            myhtml.Visible = false;



            //Response.Redirect("postlist.aspx");
           Response.Write(Msg.GetMsg("更新文章成功！", "postlist.aspx"));
            return;
        }
        else //添加文章
        {

            id = Blogs.CreatePost(db, GetLinks(db.BlogID));
            myhtml.Visible = false;


           // Response.Redirect("postlist.aspx");
            Response.Write(Msg.GetMsg("成功发表主题！", "postlist.aspx"));
        }
       
       
   
 
    }
    int GetPrice()
    {
        int price = 0;
        switch (dropPriceType.SelectedValue)
        {
            case "1":
                price = int.Parse(iptPostPrice.Value.Trim());
                break;
            case "2":
                price = int.Parse(iptPostPrice.Value.Trim()) * 10;
                break;
            case "3":
                price = int.Parse(iptPostPrice.Value.Trim()) * 1000;
                break;
            default:
                price = 0;
                break;
        }
        return price;
    }
    List<Link> GetLinks(int blogID)
    {
        List<Link> list = new List<Link>();
        foreach (ListItem li in blog_class.Items)
        {
            if (li.Selected)
            {

                Link l = new Link();
                l.BlogID = blogID;
                l.CategoryID = int.Parse(li.Value);
                l.PostID = PostID;
                list.Add(l);
            }

        }
        return list;
    }
    private void BindPost()
    {
        DayBook blog = Blogs.GetPost(PostID, 0);
        if (blog != null)
        {
            if (blog.Account != Account)
            {
                Response.Redirect("main.aspx");
                return;
            }
            this.PostEditor.Value = blog.Text;
            this.blog_title.Value = blog.Title;
            this.iptPostPrice.Value = "0";
            this.chkEnableComment.Checked = blog.EnableComment;
            this.chkIsHide.Checked = blog.Hiding;

            List<BlogCategory> cates = BlogCategories.GetBlogCategoryByPostID(PostID);
            
            if (cates.Count > 0)
            {
               BlogCategory bc = cates[0];
                    foreach (ListItem li in blog_class.Items)
                    {
                        if (bc.CategoryID.ToString() == li.Value)
                            li.Selected = true;
                    }
             
               
            }
            SetPrice(blog.Price);

            txtTags.Text = Utils.TagsToString(blog.Tags);
        }

    }
    void SetPrice(int price)
    {

        if (price >= 10)//金币
        {
            if (price % 10 == 0)
            {
                dropPriceType.SelectedValue = "2";
                iptPostPrice.Value = (price / 10).ToString();
            }
        }
        if (price >= 1000)
        {
            if (price % 1000 == 0)
            {
                dropPriceType.SelectedValue = "3";
                iptPostPrice.Value = (price / 1000).ToString();
            }
        }
    }
    private void BindCategoryList()
    {
        chkEnableComment.Text = Globals.Text["Allow"];
        chkIsHide.Text        =Globals.Text["btn_Hide"];
        //显示个人分类
        blog_class.Items.Clear();
        blog_class.DataSource = BlogCategories.GetBlogCategoryByAccount(SpacesContext.Current.Context.User.Identity.Name);
        blog_class.DataValueField = "CategoryID";
        blog_class.DataTextField = "Title";
        blog_class.DataBind();

    }
    public string Account
    {
        get { return SpacesContext.Current.Context.User.Identity.Name; }
    }
    /*
    void SetFtb()
    {
        ftbBody.ButtonPath = Globals.ApplicationPath + "/Include/ftb/xiaoxiao/"; //Globals.ApplicationPath + "/Include/ftb/office2003/";
        ftbBody.HelperFilesPath = Globals.ApplicationPath + "/Include/ftb/";

        string imgname, tmpstr;



        // ftbBody.ImageGalleryPath = Server.MapPath(Globals.ApplicationPath + "/Include/ftb/Emoticons/");
        FreeTextBoxControls.Toolbar msntb = new FreeTextBoxControls.Toolbar();
        msntb.Items.Add(FreeTextBoxControls.ToolbarItems.Separator);
        FreeTextBoxControls.ToolbarButton tbButton;
        #region 插入msn表情
        /*
        XmlDocument myxml = new XmlDocument();
        myxml.Load(Server.MapPath(Globals.ApplicationPath + "/Include/ftb/Emoticons/") + "emoticons.xml");
        XmlNodeList nodes = myxml.SelectNodes("/emoticons/emoticon");
        foreach (XmlNode node in nodes)
        {
            tbButton = new FreeTextBoxControls.ToolbarButton();
            tbButton.Title = node.Attributes["title"].InnerText;
            tbButton.Name = node.Attributes["name"].InnerText;
            imgname = Server.MapPath(Globals.ApplicationPath + "/Include/ftb/Emoticons/") + tbButton.Name + ".gif";
            System.Drawing.Image myimg = System.Drawing.Image.FromFile(imgname);
            //imgname = Globals.WebPathCombine(Request.ApplicationPath, "/Emoticons/") + tbButton.Name + ".gif";
            tbButton.Height = myimg.Height;
            tbButton.Width = myimg.Width;
            tbButton.Function = "FTB_" + tbButton.Name + "_ShowFace";
            tbButton.ScriptBlock = @"<script language=""JavaScript"">
				function " + tbButton.Function + @"(editor,htmlmode) {
				editor.focus();
				sel = editor.document.selection.createRange();
				sel.pasteHTML(""<img src='" + imgname + @"'>"");
				}
				</script>";
            msntb.Items.Add(tbButton);

            msntb.Items.Add(FreeTextBoxControls.ToolbarItems.Separator);
        

        }

        #endregion

        #region 插入QQ表情

        FreeTextBoxControls.ToolbarButton qqButton = new FreeTextBoxControls.ToolbarButton("插入梦幻表情", "mh", "FTB_InsertQQEmoticon");
        qqButton.ScriptBlock = @"<script language=""JavaScript"">
			function FTB_InsertQQEmoticon(editor,htmlmode) {
			if (htmlmode) return;
			editor.focus();

			obj = FTB_GetRangeReference(editor);
			if (obj.tagName == 'IMG') 
			{
				editor.document.execCommand('insertimage',1,'');
				return;
			}

			var folder = '" + Globals.ApplicationPath + @"/images/Emoticons/QQ';
			var galleryscript = '" + ftbBody.HelperFilesPath + @"/EmoticonsGallery.aspx?rif='+folder+'&cif='+folder;
			if (FTB_HelperFilesParameters != '') galleryscript += '&' + FTB_HelperFilesParameters;
			imgArr = showModalDialog(galleryscript,window,'help:0;status:0;resizeable:1;');

			if (imgArr != null) 
				{
					imagestring = '<IMG SRC=""' + imgArr['filename'] + '"" HEIGHT=' + imgArr['height'] + ' WIDTH=' + imgArr['width'] + ' BORDER=0>';
					sel = editor.document.selection.createRange();
					sel.pasteHTML(imagestring);
				} 
			else 
				{
			
				}
			}
			</script>";


        FreeTextBoxControls.Toolbar qqtb = new FreeTextBoxControls.Toolbar();
        qqtb.Items.Add(qqButton);
        #endregion

        #region InserCode 插入代码


        FreeTextBoxControls.ToolbarButton CodeButton = new FreeTextBoxControls.ToolbarButton("插入代码", "Code", "FTB_InsertCode");
        Unit width = new Unit("80");
        CodeButton.Width = width;
        // CodeButton.ButtonTitleMode
        CodeButton.ScriptBlock = @"<script language=""JavaScript"">
			function FTB_InsertCode(editor,htmlmode)
			 {
			if (htmlmode) return;
			editor.focus();		
			var galleryscript = '" + ftbBody.HelperFilesPath + @"/InsertCode.aspx';
			CodeString = showModalDialog(galleryscript,window,'dialogWidth:680px; dialogHeight:400px;help:0;status:0;resizeable:1;');
			if (CodeString != null) 
			{
				sel = editor.document.selection.createRange();
				sel.pasteHTML(CodeString);
			}
			}
			</script>";


        FreeTextBoxControls.Toolbar Codetb = new FreeTextBoxControls.Toolbar();
        Codetb.Items.Add(CodeButton);
        ;
        #endregion

        #region 恢复上次提交内容
        /*
        FreeTextBoxControls.ToolbarButton RestoreButton = new FreeTextBoxControls.ToolbarButton("恢复上次提交", "restore", "FTB_RestoreLastSubmit");
        width = new Unit("70");
        RestoreButton.Width = width;
        RestoreButton.ScriptBlock = @"<script language=""JavaScript"">
			function FTB_RestoreLastSubmit(editor,htmlmode)
			 {
				if(confirm('真的要恢复吗?'))
				{
					Restore(editor);
				}
			}
			</script>";
        FreeTextBoxControls.Toolbar Restoretb = new FreeTextBoxControls.Toolbar();
        Restoretb.Items.Add(RestoreButton);

        #endregion

       
        #region ToolbarStr
        string toolbarStr = @"ParagraphMenu,FontFacesMenu,FontSizesMenu|FontForeColorsMenu,FontForeColorPicker,FontBackColorsMenu,FontBackColorPicker|Bold,Italic,Underline,Strikethrough,Superscript,Subscript, ,,InsertImage,CreateLink,Unlink,RemoveFormat|JustifyLeft,JustifyRight,JustifyCenter,JustifyFull;BulletedList,NumberedList,Indent,Outdent|Cut,Copy,Paste,Delete;Undo,Redo,Print|StyleMenu,SymbolsMenu,|InsertRule,InsertDate,InsertTime,WordCount,WordClean,InsertTable";
        ftbBody.Toolbars = FreeTextBoxControls.ToolbarGenerator.ToolbarsFromString(toolbarStr);//.EnableAll;

        #endregion
        ftbBody.Toolbars.Add(qqtb);
        ftbBody.Toolbars.Add(Codetb);
         ftbBody.Toolbars.Add(Restoretb);
         ftbBody.Toolbars.Add(msntb);	

    }
    */
}
