using LJLib.Tools.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace LJLib.LocalLog
{
    internal class LocalTraceListener : TraceListener
    {
#if !(WindowsCE || PocketPC)
        private Dictionary<string, byte> oldStack = new Dictionary<string, byte>();
#endif

        private object _syncRoot = new object();

        private ILogger _logger = null;
        public bool HasStack { get; set; }
        public LocalTraceListener(ILogger logger) { _logger = logger; }
        public override void Write(string message)
        {
            lock (_syncRoot)
            {
                if (_logger != null)
                {
                    try
                    {
                        if (HasStack) // 包含堆栈信息
                        {
#if !(WindowsCE || PocketPC)
                            var stack = (new StackTrace()).ToString();
                            var key = stack;
                            var index = message.IndexOf(": ");
                            if (index >= 0)
                            {
                                key += message.Substring(0, index);
                            }
                            if (!oldStack.ContainsKey(key)) // 重复的堆栈信息不输出
                            {
                                oldStack.Add(key, 1);
                                message += "\r\n" + stack;
                                _logger.WriteLog(message);
                            }
#endif
                        }
                        else // 不包含堆栈信息
                        {
                            _logger.WriteLog(message);
                        }
                    }
                    catch (Exception ex) { }
                }
            }
        }

        public override void WriteLine(string message)
        {
            Write(message);
        }
    }
}