using irisHelper;
using irisRefactor.FrmService;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace irisRefactor.IrisThread
{
    public class FindEyesTh
    {
        private static FindEyesTh _findEyesTh = null;
        private FindEyesTh() {}
        public static FindEyesTh GetInstance()
        {
            if (_findEyesTh == null)
                _findEyesTh = new FindEyesTh();

            return _findEyesTh;
        }

        public void FindEyes()
        {
            LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "FindEyes");

            ProMemory.Tag_SleepTimer = 0;

            try
            {
                //开启计时器，搜眼时间，如果时间到了仍未搜到眼睛，则待机或开启下一轮识别
                AutoResetEvent autoEvent = new AutoResetEvent(false);
                TimerCallback timer1Delegate = new TimerCallback(Timer1ThreadMethod);
                ProMemory.timer1 = new Timer(timer1Delegate, autoEvent, 60000, 0);

                while (ProMemory.irisConfig.EyeFinderThreadRun && ProMemory.Tag_SleepTimer == 0 && !ProMemory.isSyning)
                {
                    //M++;
                    if (ProMemory.irisConfig.QueueFace.Count > 0)
                    {
                        lock (ProMemory.irisConfig.QueueFace)
                        {
                            if (ProMemory.irisConfig.QueueFace.Count > 0)
                            {
                                ProMemory.irisConfig.FaceBuffer = ProMemory.irisConfig.QueueFace.Pop();
                            }
                        }

                        if (ProMemory.irisConfig.FaceBuffer != null)
                        {
                            unsafe
                            {
                                IntPtr ptrFace = Marshal.AllocHGlobal(1280 * 960);
                                Marshal.Copy(ProMemory.irisConfig.FaceBuffer, 0, ptrFace, 1280 * 960);

                                int mark;
                                int[] posvec = new int[] { 0, 0, 0, 0, 0, 0 };

                                fixed (int* pos = &posvec[0])
                                {
                                    int* ptrPos = pos;
                                    mark = ProMemory.CaptureEye_Rec(ptrFace, ref ptrPos);
                                    int[] irisPos = { ptrPos[0], ptrPos[1], ptrPos[2], ptrPos[3], ptrPos[4], ptrPos[5] };

                                    if (mark == 1 || mark == 2)
                                    {
                                        ProMemory.jobRuning = true;
                                        lock (ProMemory.irisConfig.Q2)
                                        {
                                            ProMemory.irisConfig.Q2.Push(ProMemory.irisConfig.FaceBuffer);
                                        }

                                        lock (ProMemory.irisConfig.Q3)
                                        {
                                            ProMemory.irisConfig.Q3.Push(irisPos);
                                        }
                                        if (ProMemory.irisConfig.Key_Assess == 0)
                                        {
                                            ProMemory.irisConfig.Key_Assess = 1;

                                            //黄灯闪烁
                                            ProMemory.IoControllService.setYellowFlash(true);
                                            Thread flashThrd = new Thread(ProMemory.IoControllService.YellowFlash);
                                            flashThrd.Start();

                                            //停止timer1计时，此时只有等到Tag_EyesFound=1时该线程才会结束循环自然停止
                                            //ProMemory.timer1.Dispose();

                                            //开启质量评估线程
                                            ProMemory.irisConfig.AssessThreadRun = true;

                                            Thread m_AssessThread = new Thread(ImageQualityAssessTh.GetInstance().ImageQualityAssess);
                                            m_AssessThread.Name = "ImageQualityAssess";
                                            m_AssessThread.Start();
                                        }
                                    }

                                }

                                Marshal.FreeHGlobal(ptrFace);
                            }
                        }

                        lock (ProMemory.irisConfig.Q2)
                        {
                            if (ProMemory.irisConfig.Q2.Count >= 30)
                            {
                                ProMemory.irisConfig.Q2.Clear(); //手动控制堆栈容量
                            }
                        }

                        lock (ProMemory.irisConfig.Q3)
                        {
                            if (ProMemory.irisConfig.Q3.Count >= 30)
                            {
                                ProMemory.irisConfig.Q3.Clear(); //手动控制堆栈容量                   
                            }
                        }
                    }
                }

                if (ProMemory.Tag_SleepTimer == 1) //待机时间到,仍未找到眼睛
                {
                    if (ProMemory.m_bGrabbing)
                    {
                        if (ProMemory.IoControllService.getSensorVal() == 0) //未再次触发,待机
                        {
                            if (ProMemory.formType == "1")
                                Form1.GetInstance().ReInitializeToSleep();
                            else if (ProMemory.formType == "2")
                                Form2.GetInstance().ReInitializeToSleep();
                            Thread.Sleep(200);
                            ProMemory.cameraController.ContinuousShot_TriggerOn();
                        }
                        else //已再次触发,继续下一轮识别
                        {
                            ProMemory.cameraController.ContinuousShot_TriggerOff();
                        }
                    }
                }
                
                ProMemory.timer1.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "眼睛搜索线程CatchError:" + ex);
            }

        }

        //在设定的时间内没有搜到眼睛，回调方法
        public void Timer1ThreadMethod(Object State)
        {
            ProMemory.Tag_SleepTimer = 1;
        }

    }
}