using LJLib.Tools.File;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace LJLib.TextLog
{
    internal class RequestLogger : ILogger
    {
        private readonly string _logDir;
        private readonly object _syncRoot = new object();

        public RequestLogger()
        {
            _logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (!Directory.Exists(_logDir)) Directory.CreateDirectory(_logDir);
        }

        /// <summary>
        /// 获取今天的日志文件全路径
        /// </summary>
        private string GetTodayLogFile()
        {
            string fileName = $"REQUEST_{DateTime.Now:yyyyMMdd}.log";
            return Path.Combine(_logDir, fileName);
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        public void WriteLog(string msg)
        {
            try
            {
                lock (_syncRoot)
                {
                    string filePath = GetTodayLogFile();

                    using (StreamWriter sw = new StreamWriter(filePath, true))
                    {
                        sw.WriteLine("====================================================================");
                        sw.WriteLine($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                        sw.WriteLine("--------------------------------------------------------------------");
                        sw.WriteLine(msg);
                        sw.WriteLine("====================================================================");
                        sw.WriteLine();
                    }
                }
            }
            catch(Exception ex)
            {
                // 这里可考虑写到系统事件日志或忽略
                Trace.Write(ex);
            }
        }
    }
}
