using System;
using System.Collections.Generic;
using System.IO;

namespace XGame.Framework.Logger
{
    internal class WriterRepository : IDisposable
    {
        private Dictionary<LogType, ILogWriter> _writerMap = new Dictionary<LogType, ILogWriter>();

        public ILogWriter GetWriter(LogType logType)
        {
            ILogWriter writer = null;
            lock (_writerMap)
            {
                if (!_writerMap.TryGetValue(logType, out writer))
                {
                    var logDirectory = logType == LogType.Code ? LogDefine.CodeLogPath : LogDefine.EventLogPath;
                    if (!Directory.Exists(logDirectory))
                    {
                        Directory.CreateDirectory(logDirectory);
                    }
                    var mmfile = new MMFile(logType == LogType.Code ? LogDefine.CodeMMFPath : LogDefine.EventMMFPath, LogDefine.CacheCapacityLimit);
                    writer = new LogWriter(logType, mmfile, null);
                    _writerMap.Add(logType, writer);
                }
            }
            return writer;
        }
        public void Dispose()
        {
            lock (_writerMap)
            {
                foreach (var item in _writerMap)
                {
                    (item.Value as IDisposable)?.Dispose();
                }
                _writerMap.Clear();
            }
        }
    }
}
