using irisDataBase;
using irisDataBase.Service;
using IrisDoor;
using irisHelper;
using irisIoControll;
using irisIoControll.Service;
using irisMemory;
using irisRefactor.IrisCamera;
using irisRefactor.IrisScoket;
using System;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace irisRefactor
{
    public class ProMemory
    {
        public static String formType;
        public static ProConfig proConfig;
        public static AppConfig appConfig;
        public static IrisConfig irisConfig;
        public static IdentifyConfig identifyConfig;
        public static IoControllService IoControllService = (IoControllService)IrisIoControllObject.getEntity();
        public static IrisDataService irisDataService = (IrisDataService)IrisDataBaseObject.getEntity("IrisDataService");
        public static IrisPersonViewService irisPersonViewService = (IrisPersonViewService)IrisDataBaseObject.getEntity("IrisPersonView");
        public static IrisRecordsService irisRecordsService = (IrisRecordsService)IrisDataBaseObject.getEntity("IrisRecords");
        public static IrisSynchDataService irisSynchDataService=(IrisSynchDataService)IrisDataBaseObject.getEntity("IrisSynchData");
        public static IrisPermisionService irisPermisionService = (IrisPermisionService)IrisDataBaseObject.getEntity("IrisPermision");
        public static IrisDeviceService irisDeviceService = (IrisDeviceService)IrisDataBaseObject.getEntity("IrisDevice");

        public static bool goingToCloseForm = false; /*是否正在关闭程序标志*/
        public static bool m_bGrabbing = false; /*是否正在拍摄标志*/
        //public static int Tag_SleepTimer = 0;
        //public static int Tag_IdentifyTimer = 0;

        public static bool isSyning = false;
        public static bool jobRuning = false;

        public static bool isWait = false;//是否待机
        // public static bool findingEyes = false;//开始找眼标记

        public static string hostIp = "";

        public static System.Windows.Forms.Timer timerCamera;
        public static System.Threading.Timer timer1;
        public static System.Threading.Timer timer2;
        public static CameraController cameraController;

        public static byte[] btImage = new byte[1280 * 960];

        /// <summary>
        /// //////
        /// </summary>
        public static int tempRegion; //温度区间1-温度过低，2-体温正常，3-体温异常，4-温度过高
        //public static String tempString;
        public static bool isSleeping = false;

        [DllImport("User32.dll")]
        static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int Iparam);
        const int WM_CLOSE = 0X0010;
        [DllImport("CaptureEye_Rec.dll", EntryPoint = "CaptureEye_Rec")]
        public static extern unsafe int CaptureEye_Rec(IntPtr Data, ref int* pos);
        [DllImport("AssessFocus_RecSY.dll", EntryPoint = "AssessFocus_Rec")]
        public static extern unsafe int AssessFocus_Rec(IntPtr Data, int[] Pos, ref byte* irisImage, ref byte* irisImage2);


        public static StringBuilder stringBuilder = new StringBuilder();
        public static StringBuilder tempString = new StringBuilder();
        /// <summary>
        /// 注意初始不要涉及数据库
        /// </summary>
        public static void InitProMemory()
        {
            try
            {
                formType = ConfigHelper.GetAppConfig("formType");

                proConfig = ProConfig.GetInstance();
                appConfig = AppConfig.GetInstance();
                irisConfig = IrisConfig.GetInstance();
                identifyConfig = IdentifyConfig.GetInstance;

                // 相机控制
                cameraController = CameraController.GetInstance();

                //GetHostIPv4();
                hostIp = ConfigHelper.GetAppConfig("hostIp");
                //嵌入式电脑I/O口初始化
                IoControllService.initIO();

                //检测并连接相机
                timerCamera = new System.Windows.Forms.Timer();
                timerCamera.Tick += new EventHandler(cameraController.TimerCamera_Tick);
                timerCamera.Interval = 3000; // 延时3000ms执行，在CameraController中判断是否销毁定时器
                timerCamera.Start();

                //初始化门禁，若有权限链接串口
                DoorSystem doorSystem = new DoorSystem();

                //数据库链接
                Thread connectServerThread = new Thread(ConnectDatabase);
                connectServerThread.Start();
            }
            catch (Exception ex) {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, ex.Message);
            }
        }

        private static void ConnectDatabase()
        {
            if (DatabaseLocal.OpenDB(appConfig.DbLocalConfig) == 0)
            {
                proConfig.CodeListMgr = new IrisCodeListMgr(); //匹配列表初始化
                proConfig.CodeListMgr.CreateList(irisDataService.getAllIrisCodeLocal());//加载匹配列表
            }
            else
            {
                if (ProMemory.appConfig.Language == 1)
                    MessageBox.Show("本地数据库连接失败，程序即将关闭!", "异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    MessageBox.Show("database connection fialed","message");
                Application.ExitThread();
                Application.Exit();
            }

            SocketHelper socket = new SocketHelper();
            socket.start();

            string msg = "初始化数据库连接成功";
            LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, msg);
        }

        public static void Close() {
            goingToCloseForm = true;

            irisConfig.IdentifyThreadRun = false;
            irisConfig.AssessThreadRun = false;
            irisConfig.EyeFinderThreadRun = false;
            //cameraController.Grabbing();
            cameraController.CloseCamera();

            IoControllService.YellowOff();
            IoControllService.RedOff();
            IoControllService.GreenOff();

            DatabaseLocal.CloseDB();
        }

        //获取本机IP
        private static void GetHostIPv4()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

            if (hostEntry.AddressList.Length > 0)
            {
                foreach (IPAddress ipAddr in hostEntry.AddressList)
                {
                    if (ipAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        //hostIp = ipAddr.ToString();
                        String ip = ipAddr.ToString();
                        if (ip != null && ip != "")
                            ConfigHelper.UpdateAppConfig("hostIp", ip);
                        break;
                    }
                }
            }
        }


    }
}