using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Timers;

namespace Khd.Core.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            #region 定时删除日志
            // 设置定时器，间隔24小时（86400000毫秒）
            System.Timers.Timer timer = new System.Timers.Timer(86400000);

            timer.Elapsed += TimerElapsed;
            timer.AutoReset = true;
            timer.Start();

            // 初次执行删除操作
            DeleteOldLogFiles();
            #endregion
            CreateHostBuilder(args).Build().Run();
        }

        private static void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            DeleteOldLogFiles();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://0.0.0.0:5001");
                    webBuilder.UseStartup<Startup>();
                });
        }
        private static void DeleteOldLogFiles()
        {
            string logDirectory = AppDomain.CurrentDomain.BaseDirectory + "logs"; // 替换为实际的日志文件夹路径
            DateTime cutoffDate = DateTime.Now.AddDays(-3); // 3天前的日期

            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(logDirectory);

                // 获取日志文件并筛选出需要删除的文件
                FileInfo[] logFiles = dirInfo.GetFiles("*.log")
                    .Where(file => file.LastWriteTime < cutoffDate)
                    .ToArray();

                foreach (var file in logFiles)
                {
                    // 删除文件
                    file.Delete();
                    Console.WriteLine($"已删除文件：{file.Name}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除日志文件时出现错误：{ex.Message}");
            }
        }
    }
}