using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using parkMonitor.entity;
using System.Configuration;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using parkMonitor.tools;
using parkMonitor.server.uiLogServer;
using parkMonitor.LOG;

namespace parkMonitor.server.WebThread
{
    /// <summary>
    /// web线程类，接收用户指令
    /// </summary>
    public class CentralForWeb : IEquipments
    {
        public MultiSocketThread multiSocketThread { set; get; }
        public static BlockingQueue blockingQueue = new BlockingQueue();
        Int32 port;
        IPAddress localAddr;
        bool isClosing;

        public AbstractMessage GetMessage()
        {
            return (AbstractMessage)blockingQueue.Dequeue();
        }

        public void SetMessage(AbstractMessage message)
        {
            //multiSocketThread.SendMessage(message);
        }

        private void WebConnect(TcpListener listener)
        {
            try
            {
                if (listener != null)
                {
                    //得到包含客户端信息的套接字                
                    var tcpClient = listener.AcceptTcpClient();
                    //创建消息服务线程对象 
                    //把multiSocket类的run方法委托给线程  
                    multiSocketThread = new MultiSocketThread(tcpClient);
                    Thread newThread = new Thread(multiSocketThread.Run);
                    newThread.IsBackground = true;
                    newThread.Start();
                }
            }
            catch (Exception e)
            {
                if (multiSocketThread != null)
                    multiSocketThread.Close();
                Console.WriteLine(e.Message);
                throw new Exception();
            }
        }

        private void Run()
        {
            bool linked = false;
            Task.Factory.StartNew(() =>
            {
                TcpListener listener = null;
                try
                {
                    listener = LazySingleton.GetInstance(localAddr, port);
                    listener.Start();
                    linked = true;
                }
                catch (Exception) { UILogServer.ins.error("未能与Web服务器连接,本地ip错误或网络异常"); Log.WriteLog(LogType.NOT_DATABASE, LogFile.ERROR, "与Web服务器连接失败"); linked = false; }
                while (!isClosing)
                {
                    try
                    {
                        while (linked)
                        {
                            WebConnect(listener);
                        }
                        if (!linked)
                        {
                            throw new Exception();
                        }
                    }
                    catch (Exception)
                    {
                        //Task.Factory.StartNew(() =>
                        //{
                        MyTimer mt = new MyTimer();
                        mt.StartTiming();
                        while (!linked)
                        {
                            Thread.Sleep(10000);
                            try
                            {
                                listener = LazySingleton.GetInstance(localAddr, port);
                                listener.Start();
                                linked = true;
                                UILogServer.ins.log("web已成功重连");
                                Log.WriteLog(LogType.NOT_DATABASE, LogFile.INFO, "web已成功重连");
                                break;
                            }
                            catch (Exception)
                            {
                                mt.EndTiming();
                                int count=0;
                                if (mt.IsLonger(30, 1, true, out count))
                                {
                                    UILogServer.ins.error("未能与Web服务器连接,本地ip错误或网络异常");
                                    Log.WriteLog(LogType.NOT_DATABASE, LogFile.ERROR, "与Web服务器连接失败");
                                }
                            }
                        }
                        //});
                    }
                    Thread.Sleep(5000);
                }
                if (multiSocketThread != null)
                    multiSocketThread.Close();
            });
        }

        public void Start()
        {
            string strTemp = ConfigurationManager.AppSettings["WebConfig"];
            string[] strArray = strTemp.Split(':');
            string ipstr = strArray[0];
            string portstr = strArray[1];

            try
            {
                port = Convert.ToInt32(portstr);
                localAddr = IPAddress.Parse(ipstr);
            }
            catch (Exception) { }

            //Thread thread = new Thread(() =>
            //{

            //});
            //thread.IsBackground = true;
            //thread.Start();
            Run();
        }

        public void Stop()
        {
            isClosing = true;
        }
    }
}
