using GxIAPINET;
using irisDataBase;
using irisHelper;
using irisRefactor.FrmService;
using irisRefactor.IrisThread;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace irisRefactor.IrisCamera
{
    public class CameraController
    {
        DH_CameraOperator dH_CameraOperator = new DH_CameraOperator();

        private static CameraController _cameraController = null;
        private CameraController()
        {
            
        }
        public static CameraController GetInstance()
        {
            if (_cameraController == null)
                _cameraController = new CameraController();

            return _cameraController;
        }

        public void TimerCamera_Tick(Object sender, EventArgs myEventArgs)
        {
            LogHelper.WriteDebugLog(MethodBase.GetCurrentMethod().DeclaringType, "DH Camera Tick Begin");

            bool openCam = false;
            if (ProMemory.formType == "1")
            {
                openCam = dH_CameraOperator.OpenDevice(Form1.GetInstance().picLive);
            } else if (ProMemory.formType == "2")
            {
                openCam = dH_CameraOperator.OpenDevice(Form2.GetInstance().picLive);
            }
            
            if (DatabaseLocal.mySqlConnect.State != ConnectionState.Closed)
            {
                DatabaseLocal.CloseDB();
            }
            
            //打开设备,开始采集
            if (openCam == true)
            {
                ProMemory.timerCamera.Dispose();
                LogHelper.WriteDebugLog(MethodBase.GetCurrentMethod().DeclaringType, "DH Camera Tick Dispose");

                ProMemory.IoControllService.GreenOff();
                ProMemory.IoControllService.RedOff();
                ProMemory.IoControllService.YellowOn();

                // 打开摄像头
                ConnectCamera();
                // ContinuousShot_TriggerOff();

                // 初始化找眼预处理线程
                Thread thPreIdentify = new Thread(PreIdentifyTh.GetInstance.FindEyes)
                {
                    Name = "PreIdentifyThread" + DateTime.Now.ToString("[MMddHHmmss]")
                };
                thPreIdentify.Start();
            }
        }
        
        //连接相机
        private void ConnectCamera()
        {
            try
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "CAMERA,START");
                dH_CameraOperator.StartDevice();

                // 开始取流
                ProMemory.m_bGrabbing = true;

                // 最重要的操作，将findingEyes的变量设置为true，表示可以开始找眼
                ProMemory.identifyConfig.FlagFindingEye = true;
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "connect camera failed：" + e.Message);
            }
        }

        /**
         * 待机
         * 持续监测感应模块，有外触发到来则重新开始工作
         */
        public void ContinuousShot_TriggerOn()
        {
            try
            {
                ProMemory.isWait = true;
                ProMemory.jobRuning = false;

                // 先停止取流
                // StopGrabbing();
                //GC.Collect();
                CloseCamera();

                LogHelper.WriteDebugLog(MethodBase.GetCurrentMethod().DeclaringType, "触发待机线程：" + Thread.CurrentThread.Name);
                
                // 循环检测是否有外触发，重新开始工作
                while (ProMemory.isWait)
                {
                    // 通过检测嵌入式板子输入端口0电平状态判断外触发是否到来
                    if (ProMemory.IoControllService.getSensorVal() == 1) 
                    {
                        // 外触发到来，开始采集
                        LogHelper.WriteDebugLog(MethodBase.GetCurrentMethod().DeclaringType, "外触发到来");
                        ProMemory.IoControllService.YellowOn();
                        ProMemory.isWait = false;
                        // Grabbing();

                        // 重新开始工作，开始找眼
                        dH_CameraOperator.StartDevice();
                        ProMemory.m_bGrabbing = true;
                        ProMemory.identifyConfig.FlagFindingEye = true;
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "外触发采集错误 ：" + e);
                MessageBox.Show("ContinuousShot_TriggerOn:" + e.Message);
            }
        }

        /**
         * 正常工作
         */
        public void ContinuousShot_TriggerOff()
        {
            try
            {
                LogHelper.WriteDebugLog(MethodBase.GetCurrentMethod().DeclaringType, "外触发到来，当前线程：" + Thread.CurrentThread.Name);
                
                // 重置界面
                if (ProMemory.formType == "1") Form1.GetInstance().ReInitialize();
                else if (ProMemory.formType == "2") Form2.GetInstance().ReInitialize();

                ProMemory.IoControllService.YellowOn();

                // 持续工作，重新开始找眼
                ProMemory.identifyConfig.FlagFindingEye = true;
                // Grabbing();
            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "普通采集错误 ：" + e);
            }
        }
        
        //断开相机
        public void CloseCamera()
        {
            try
            {
                //关闭设备
                //m_pOperator.Close();
                dH_CameraOperator.StopDevice();

                //取流标志位清零
                ProMemory.m_bGrabbing = false;
            }
            catch (Exception e)
            {
                LogHelper.WriteErrorLog(MethodBase.GetCurrentMethod().DeclaringType, "断开相机错误：" + e);
                MessageBox.Show("CloseCamera:" + e.Message);
            }
        }

        public void Grabbing()
        {
            if (ProMemory.isSyning)
            {
                LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, "数据更新过程中");
                return;
            }
            try
            {
                string msg = "";

                lock (this)
                {
                    if (ProMemory.m_bGrabbing)
                    {
                        // dH_CameraOperator.stop();
                        ProMemory.m_bGrabbing = !ProMemory.m_bGrabbing;
                    }

                    msg += "开始取流成功;";
                    ProMemory.m_bGrabbing = !ProMemory.m_bGrabbing;
                    Thread.Sleep(1000);
                }

                LogHelper.WriteInfoLog(MethodBase.GetCurrentMethod().DeclaringType, msg);
                // ProMemory.findingEyes = true;

                while (!ProMemory.isWait && !ProMemory.irisConfig.AssessThreadRun)
                {
                    Thread.Sleep(100);
                    IImageData imageData = dH_CameraOperator.TriggerGetOneFrame();
                    IntPtr image = imageData.GetBuffer();
                    SaveImageTh.GetInstance.SaveImage(image);
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "StartGrabbingError");
            }
            finally
            {
            }
        }
    }
}