using System.Collections.Generic;

namespace ynhtm.Theme.Template.Post
{
    using Common;
    using DBUtility;

    /// <summary>
    /// 文章页模板。
    /// </summary>
    public abstract class Template : TemplateBase<Model.Post>, ITemplatePrevNext<Model.Post>
    {
        Model.Category category;
        /// <summary>
        /// 获取文章栏目，没有返回 null。
        /// </summary>
        public Model.Category Category
        {
            get
            {
                if (this.Model.CategoryID == null) return null;
                if (this.category == null)
                {
                    var category = new BLL.Category();
                    this.category = category.GetByCategoryID(this.Model.CategoryID.Value);
                }
                return this.category;
            }
        }

        Model.Post prevItem;
        /// <summary>
        /// 上一篇文章。
        /// </summary>
        public Model.Post PrevItem
        {
            get
            {
                if (this.prevItem == null)
                {
                    var post = new BLL.Post();
                    this.prevItem = post.GetPrevItem(this.Model.PostID, this.Model.CategoryID);
                }
                return this.prevItem;
            }
        }

        Model.Post nextItem;
        /// <summary>
        /// 下一篇文章。
        /// </summary>
        public Model.Post NextItem
        {
            get
            {
                if (this.nextItem == null)
                {
                    var post = new BLL.Post();
                    this.nextItem = post.GetNextItem(this.Model.PostID, this.Model.CategoryID);
                }
                return this.nextItem;
            }
        }

        /// <summary>
        /// 获取指定数量的评论。
        /// </summary>
        /// <param name="count">评论数量（必须）。</param>
        /// <param name="order">排序（为空以系统设置顺序）。</param>
        /// <returns>返回评论集合，无论是否包含评论都返回。</returns>
        public virtual List<Model.Comment> GetCommentList(int count, string order = null)
        {
            var setting = new BLL.Setting();
            var settingItem = setting.Get();
            var comment = new BLL.Comment();
            if (order.IsNullOrWhiteSpace()) order = "ORDER BY " + DAL.Comment.SQL_TABLE + "." + DAL.Comment.COMMENTID + (settingItem.CommentSort == 1 ? " DESC" : " ASC");
            return comment.GetList(count, 1, DbBase.GetQuery().BracketBegin().Equal(DAL.Comment.SQL_TABLE + "." + DAL.Comment.ISAUDIT, true).Or().Equal(DAL.Comment.SQL_TABLE + "." + DAL.Comment.IPADDR, this.Request.UserHostAddress).BracketEnd().And().Equal(DAL.Comment.SQL_TABLE + "." + DAL.Comment.POSTID, this.Model.PostID), order).ToList<Model.Comment>(DAL.Comment.FillItem);
        }

        public override void Clear()
        {
            this.category = null;
            this.prevItem = null;
            this.nextItem = null;
            base.Clear();
        }
    }
}