using DSWeb.Common.DB;
using log4net;
using Quartz;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
using System.Text.RegularExpressions;

namespace DSWeb.Job.Common
{
    /// <summary>
    /// 压缩日志 
    /// </summary>
    public class LogZipJob : IJob
    {
        private ILog logger = LogManager.GetLogger("LogZipJob");

        public void Execute(IJobExecutionContext context)
        {
            logger.Debug($"准备压缩日志文件");
            string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Logs");
            logger.Debug(logPath);
            string[] files = Directory.GetFiles(logPath);
            string regex = "^(debug|error)\\.log(\\.[0-9]{1,3})?$";
            if (files.Length > 0)
            {
                string zipFile = Path.Combine(logPath, $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.zip");
                string tempPath = Path.Combine(logPath, "temp");
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
                Directory.CreateDirectory(tempPath);

                try
                {
                    foreach (string file in files)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        if (!Regex.IsMatch(fileInfo.Name, regex) && fileInfo.Extension != ".zip")
                        {
                            logger.Debug($"发现待压缩文件:{fileInfo.Name}");

                            File.Copy(file, Path.Combine(tempPath, fileInfo.Name));
                            File.Delete(file);
                        }
                    }
                    FastZip fastZip = new FastZip();
                    fastZip.CreateZip(zipFile, tempPath, true, "");
                    Directory.Delete(tempPath, true);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    logger.Error(ex.StackTrace);
                }
            }
            logger.Debug($"压缩日志文件完成");
        }
    }
}