using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using static ControllerDllCSharp.ClassLibControllerDll;
namespace ProductionControl.Device
{
    public class LightDev : IDisposable
    {
        #region 第二款光源(Rsee) X86DLL 64位可用吗？
        //comHandle = RseeController_OpenCom(PortName, 19200, true);  //Com_Handle!=0成功
        [DllImport(@"RseeController.dll", EntryPoint = "RseeController_OpenCom",  CallingConvention = CallingConvention.Cdecl)]
        private extern static int RseeController_OpenCom(string szPort, int Baud_rate, bool overlapped);

        //关闭传上面打开返回的comHandle
        [DllImport(@"RseeController.dll", EntryPoint = "RseeController_CloseCom",  CallingConvention = CallingConvention.Cdecl)]
        private extern static bool RseeController_CloseCom(int comHandle);

        //设置新值 channel通道号:1-4
        [DllImport(@"RseeController.dll", EntryPoint = "RseeController_PM_D_BRTSetChannel",  CallingConvention = CallingConvention.Cdecl)]
        private extern static int RseeController_PM_D_BRTSetChannel(int comHandle, int channel, int range);

        //读取当前值
        [DllImport(@"RseeController.dll", EntryPoint = "RseeController_PM_D_BRTReadChannel",  CallingConvention = CallingConvention.Cdecl)]
        private static extern unsafe int RseeController_PM_D_BRTReadChannel(int comHandle, int channel, int* range);

        #endregion
        private int Com_Handle;
        private LightDevNameEnum devName;
        private long portHandle; 
        /// <summary>
        /// 光源亮度值
        /// </summary>
        public int DigitalValue { get; private set; }
        
        public Action<WarningEnum, string> WarningEvent;
        /// <summary>
        /// 光源亮度值<通道号,亮度值0-255>
        /// </summary>
        public Action<int, int> DigitalEvent; 
        /// <summary>
        /// 是否打开设备成功
        /// </summary>
        public bool IsInit { get; private set; } = false;
        //private System.Timers.Timer timer = new System.Timers.Timer();
        public LightDev(LightDevNameEnum _devName)
        {
            devName = _devName;
        }
        public bool start(int comNum)
        {
            try
            {
                if (devName == LightDevNameEnum.康仕达)
                {
                    int result = CreateSerialPort(comNum, ref portHandle);  //创建串口
                    if (result != SUCCESS)
                        throw new Exception($"打开光源设备(COM{comNum})失败: {result}");
                }
                else if (devName == LightDevNameEnum.锐视)
                {
                    Com_Handle = RseeController_OpenCom("COM"+ comNum, 19200, true); 
                    if (Com_Handle == 0)
                        throw new Exception($"打开光源设备(COM{comNum})失败;");
                }
                else
                    throw new Exception($"打开光源设备失败，未知设备型号！");

                IsInit = true;
                //timer.Elapsed += Timer_Elapsed;
                //timer.Interval = 100;
                //timer.Enabled = true;

                return true;
            }
            catch(Exception ex)
            {
                WarningEvent?.Invoke(WarningEnum.High,ex.Message);
                return false;
            }
        }
        public void stop()
        {
            if (!IsInit) return;
            try
            {
                IsInit = false;
                //timer.Elapsed -= Timer_Elapsed;
                //timer.Stop();
                if (devName == LightDevNameEnum.康仕达)
                    ReleaseSerialPort(portHandle);  //断开串口 
                else if (devName == LightDevNameEnum.锐视)
                    RseeController_CloseCom(Com_Handle);
            }
            catch { }
        }
        public unsafe int getDigitalValue(int channelIndex)
        {
            if (!IsInit) return -1;

            int value = 0;
            if (devName == LightDevNameEnum.康仕达)
            {
                if (GetDigitalValue(ref value, channelIndex, portHandle) != SUCCESS)
                    return -1;
            }
            else if (devName == LightDevNameEnum.锐视)
            { 
                if (RseeController_PM_D_BRTReadChannel(Com_Handle, channelIndex, &value) != 0)
                    return -1; 
            }
            else 
                return -1;

            DigitalEvent?.Invoke(channelIndex, value);
            return value;  
        }
        /// <summary>
        /// 设置亮度值 
        /// </summary>
        /// <param name="channelIndex">通道</param>
        /// <param name="value">0-255</param>
        /// <returns></returns>
        public bool setDigitalValue(int channelIndex, int value)
        {
            if (!IsInit) return false;
            Task.Factory.StartNew(() => {
                if (devName == LightDevNameEnum.康仕达)
                {
                    if (SetDigitalValue(channelIndex, value, portHandle) != SUCCESS)
                        return;// false;
                }
                else if (devName == LightDevNameEnum.锐视)
                {
                    if (RseeController_PM_D_BRTSetChannel(Com_Handle, channelIndex, value) != 0)
                        return;// false;
                }
            });
            
            return true;
        }
      
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!IsInit) return;
             
        }
         

        public void Dispose()
        {
            stop();
        }
    }
}
