using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Caching;

namespace ynhtm.BLL
{
    using Common;
    using DBUtility;

    /// <summary>
    /// 网站设置操作。
    /// </summary>
    public class Setting
    {
        public const string AUTHCODEKEY = "Authcode";
        public const string ALLOWEDEXTS = @"\.(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$";
        public const string ALLOWEDPICEXTS = @"\.(bmp|gif|jpeg|jpg|png)$";
        const string CACHEKEY = "Setting";
        public static string UPFILEPATH;

        static Setting()
        {
            UPFILEPATH = "/" + Utils.PathEncode(ConfigurationManager.AppSettings["Upfile"].IifNullOrWhiteSpace("upfile").Trim('~'));
        }

        /// <summary>
        /// 插入网站设置实例到数据库。
        /// </summary>
        /// <param name="item">网站设置实例。</param>
        public void Insert(Model.Setting item)
        {
            DAL.Setting.Insert(item);
        }

        /// <summary>
        /// 取得网站设置实例，默认先通过缓存读取，要取得最新的实例请先移除缓存的实例。
        /// </summary>
        /// <returns>返回网站设置实例，没有将返回 null 。</returns>
        public Model.Setting Get()
        {
            var result = HttpRuntime.Cache.Get(CACHEKEY) as Model.Setting;
            if (result == null)
            {
                result = DAL.Setting.Get();
                HttpRuntime.Cache.Insert(CACHEKEY, result, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
            }
            return result;
        }

        /// <summary>
        /// 更新网站设置。
        /// </summary>
        /// <param name="item">网站设置实例。</param>
        /// <returns>返回受到影响的行数。</returns>
        public int Update(Model.Setting item)
        {
            this.RemoveCache();
            return DAL.Setting.Update(item);
        }

        /// <summary>
        /// 删除网站设置。
        /// </summary>
        /// <returns>返回受到影响的行数。</returns>
        public int Delete()
        {
            return DAL.Setting.Delete();
        }

        /// <summary>
        /// 移除缓存中的实例。
        /// </summary>
        public void RemoveCache()
        {
            HttpRuntime.Cache.Remove(CACHEKEY);
        }

        /// <summary>
        /// 判断字符串中是否包含评论脏字。
        /// </summary>
        /// <param name="s">要判断的字符串。</param>
        /// <returns>如果包含脏字将返回 true。</returns>
        public bool HasDirty(string s)
        {
            var settingItem = this.Get();
            return Array.Exists(settingItem.CommentDirty.Split(','), a =>
            {
                if (a.IsNullOrWhiteSpace()) return false;
                return s.IndexOf(a, StringComparison.OrdinalIgnoreCase) > -1;
            });
        }

        /// <summary>
        /// 统计网站数据。
        /// </summary>
        /// <returns>返回受到影响的行数。</returns>
        public int Sumup()
        {
            using (var db = DbBase.GetDb())
            {
                this.RemoveCache();
                return db.ExecuteNonQuery("UPDATE " + DAL.Setting.SQL_TABLE + " SET " + DAL.Setting.POSTCOUNT + " = (SELECT COUNT(0) FROM " + DAL.Post.SQL_TABLE + ")," + DAL.Setting.COMMENTCOUNT + " = (SELECT COUNT(0) FROM " + DAL.Comment.SQL_TABLE + ")," + DAL.Setting.USERCOUNT + " = (SELECT COUNT(0) FROM " + DAL.User.SQL_TABLE + ")," + DAL.Setting.JOBCOUNT + " = (SELECT COUNT(0) FROM " + DAL.Job.SQL_TABLE + ")," + DAL.Setting.JOBTRYCOUNT + " = (SELECT COUNT(0) FROM " + DAL.JobTry.SQL_TABLE + ")");
            }
        }

        /// <summary>
        /// 统计附件数据。
        /// </summary>
        public void SumupUpfile()
        {
            var dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(UPFILEPATH));
            if (!dir.Exists) return;
            var count = 0;
            var size = 0L;
            foreach (var i in dir.GetFiles("*", SearchOption.AllDirectories))
            {
                count++;
                size += i.Length;
            }
            using (var db = DbBase.GetDb()) db.ExecuteNonQuery("UPDATE " + DAL.Setting.SQL_TABLE + " SET " + DAL.Setting.UPFILECOUNT + " = @" + DAL.Setting.UPFILECOUNT + "," + DAL.Setting.UPFILESIZE + " = @" + DAL.Setting.UPFILESIZE, db.CreateParameter(DAL.Setting.UPFILECOUNT, count), db.CreateParameter(DAL.Setting.UPFILESIZE, size));
            this.RemoveCache();
        }
    }
}
