using IL.Common;
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;

namespace MediII.Adapter.MsgToKCServer
{
    /// <summary>
    /// 
    /// </summary>
    public class ServiceStatusPublishManager
    {
        /// <summary>
        /// 
        /// </summary>
        static public readonly ServiceStatusPublishManager Instance = new ServiceStatusPublishManager();

        private const int MAX_LENGTH = 1000;
        private const string PIPENAME = ApplictStatic.ServerName;
        private List<LogEventArgs> _msgs;

        private ManagerImple _managerImp;
        /// <summary>
        /// 
        /// </summary>
        protected ServiceStatusPublishManager()
        {
            _managerImp = new ManagerImple(this);
            _msgs = new List<LogEventArgs>();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public void AppendMessage(LogEventArgs msg)
        {
            lock (this) _msgs.Add(msg);

            if (_msgs.Count > MAX_LENGTH)
            {
                lock (this)
                {
                    _msgs.RemoveAt(0);
                    //if (_managerImp._msgIndex == _msgs.Count) _managerImp._msgIndex -= 2;
                }
            }
        }



        public LogEventArgs GetMessage()
        {
            lock (this)
            {
                if (_msgs.Count <= 0)
                    return null;
                var data = _msgs[_msgs.Count - 1];
                _msgs.Remove(data);
                return data;
            }
        }

        class ManagerImple
        {
            private ServiceStatusPublishManager _trace;

            private Thread _thread;

            public ManagerImple(ServiceStatusPublishManager trace)
            {
                _trace = trace;
                _thread = new Thread(WriteServiceStatus);
                _thread.Start();
            }

            //public int _msgIndex = 0;

            private void WriteServiceStatus(object stats)
            {
                while (true)
                {
                    try
                    {
                        using (var serverStream = new NamedPipeServerStream(PIPENAME, PipeDirection.InOut, 10, PipeTransmissionMode.Message))
                        {
                            serverStream.WaitForConnection();

                            while (serverStream.IsConnected)
                            {
                                System.Diagnostics.Debug.WriteLine("serverStream.IsConnected", ApplictStatic.ServerName);

                                bool writeSomeMessage = false;
                                LogEventArgs logData = null;
                                while ((logData = _trace.GetMessage()) != null)
                                {
                                    var msg = string.Format("时间:{0}  是否成功:{1} 消息ID:{2} 消息内容:{3}  ", logData.LogTime, string.IsNullOrEmpty(logData.LogModel.ErrorMsg),  logData.LogModel.MessageID,
                                     logData.LogModel.Message);
                                    if (!string.IsNullOrEmpty(logData.LogModel.ErrorMsg))
                                    {
                                        msg += " 错误消息:"+logData.LogModel.ErrorMsg;
                                    }
                                    byte[] bytes = Encoding.UTF8.GetBytes(msg);
                                    serverStream.Write(bytes, 0, bytes.Length);
                                    serverStream.Flush(); 
                                    writeSomeMessage = true;
                                    Thread.Sleep(100);
                                }



                                //while (_msgIndex < _trace._msgs.Count)
                                //{
                                //    var logData = _trace._msgs[_msgIndex];
                                //    var msg = string.Format("时间:{0}  是否成功:{1} 消息ID:{2} 消息内容:{3} 错误信息:{4} ", logData.LogTime, string.IsNullOrEmpty(logData.LogModel.ErrorMsg), logData.LogModel.MessageID,
                                //        logData.LogModel.Message, logData.LogModel.ErrorMsg);
                                //    byte[] bytes = Encoding.UTF8.GetBytes(msg);
                                //    serverStream.Write(bytes, 0, bytes.Length);
                                //    serverStream.Flush();
                                //    _msgIndex++;
                                //    writeSomeMessage = true;
                                //}

                                if (!writeSomeMessage)
                                {
                                    byte[] bytes = Encoding.UTF8.GetBytes("无消息输出");
                                    serverStream.Write(bytes, 0, bytes.Length);
                                    serverStream.Flush();
                                    Thread.Sleep(1000 * 10);
                                }
                                Thread.Sleep(1000);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString(), ApplictStatic.ServerName);
                    }
                }

            }
        }
    }
}
