using parkMonitor.entity;
using parkMonitor.model;
using parkMonitor.server;
using parkMonitor.server.CoreThread;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Threading;
using parkMonitor.LOG;
using parkMonitor.Database2;

namespace parkMonitor.bll
{
    /// <summary>主业务逻辑</summary>
    public class MainBll
    {
        public void init()
        {
            //中控状态监控服务
            PcStatusServer.ins.start();
            //监控线程
            //PLCMonitorServer.ins.Start();
            var monitorThread = EquipmentSimpleFactory.ins.CreateEquipment(EquipmentName.Monitor);
            if (monitorThread != null)
            {
                monitorThread.Start();
            }
            //核心线程
            var coreThread = EquipmentSimpleFactory.ins.CreateEquipment(EquipmentName.Core);
            if (coreThread != null)
            {
                Task.Factory.StartNew(() =>
                {
                    coreThread.Start();
                    (coreThread as ICoreThreadDoWorking).BeginWorking();
                });
            }


            //Connection conn = null;
            //try
            //{
            //    conn = ConnectionPoolManager.GetConnection(CoreThreadTest2.remoteBQ); //从连接池获取连接对象；
            //    if (conn.state == System.Data.ConnectionState.Open)
            //    {
            //        Console.WriteLine(conn.state + "hello");
            //    }
            //    else
            //    {
            //        conn.Close();
            //    }

            //    string sql = "select * from user";
            //    MySqlCommand cmd = new MySqlCommand(sql, conn.mySqlConnection);
            //    MySqlDataReader rdr = cmd.ExecuteReader();
            //    while (rdr.Read())
            //    {
            //        Console.WriteLine(rdr[0] + "---------" + rdr[1] + "---------" + rdr[2]);
            //    }
            //    Thread.Sleep(5000);
            //    rdr.Close();
            //    ConnectionPoolManager.ReleaseConnection(conn,CoreThreadTest2.remoteBQ);

            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message + "==============" + "数据库连接已断开，请检查网络连接状态，然后重置连接");
            //    Thread.Sleep(10000);
            //    ConnectionPoolManager.ResetConnPooling(10, ConnectionPoolManager.remoteConf,CoreThreadTest2.remoteBQ);
            //}

           
            //主窗口关闭事件
            CmdServer.ins.listen(CmdType.MainWinClosed, () =>
            {
                ConnectionPoolManager.CloseAll(EntityForCore.remoteBQ);
                //ConnectionPoolManager.CloseAll(EntityForCore.localBQ);
                coreThread.Stop();
                monitorThread.Stop();
            });
        }      
    }
}
