using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetSDKCS;
using System.Runtime.InteropServices;
using System.Windows.Threading;

namespace NetClient
{
    /// <summary>
    /// singleton class
    /// </summary>
    public sealed class BaseDevice : DispatcherObject
    {
        /// <summary>
        /// disconnect callback.
        /// </summary>
        private readonly fDisConnectCallBack m_disConnect;

        /// <summary>
        /// reconnect callback,
        /// </summary>
        private readonly fHaveReConnectCallBack m_ReConnectCallBack;

        /// <summary>
        /// disconnect event used in BaseClient.
        /// </summary>
        private event DeviceHandler DisConnectChanged;

        /// <summary>
        /// reconnect event used in BaseClient.
        /// </summary>
        private event DeviceHandler ReConnectChanged;

        /// <summary>
        /// disconnect event trigger.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="args">device event args</param>
        private void OnDisConnectChanged(object sender, DeviceEventArgs args)
        {
            if (DisConnectChanged != null)
            {
                DisConnectChanged(sender, args);
            }
        }

        /// <summary>
        /// reconnect event trigger
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="args">device event args</param>
        private void OnReConnectChanged(object sender, DeviceEventArgs args)
        {
            if (ReConnectChanged != null)
            {
                ReConnectChanged(sender, args);
            }
        }

        /// <summary>
        /// get singleton object
        /// </summary>
        /// <returns></returns>
        public static BaseDevice GetInstance()
        {
            lock (ClientManager.InitLock)
            {
                ClientManager.ClientCount++;
            }
            if (ClientManager.Instance == null)
            {
                lock (ClientManager.InitLock)
                {
                    if (ClientManager.Instance == null)
                    {
                        ClientManager.Instance = new BaseDevice();
                    }
                }
            }
            return ClientManager.Instance;
        }

        private BaseDevice()
        {
            m_disConnect = new fDisConnectCallBack(DisConnect);
            m_ReConnectCallBack = new fHaveReConnectCallBack(ReConnectCallBack);
            Init();
        }

        /// <summary>
        /// subscription disconnect event.
        /// </summary>
        /// <param name="handler">device handler</param>
        public void AddDisConnectHandler(DeviceHandler handler)
        {
            DisConnectChanged += handler;
        }

        /// <summary>
        /// unsubscription disconnect event.
        /// </summary>
        /// <param name="handler"></param>
        public void RemoveDisConnectHandler(DeviceHandler handler)
        {
            DisConnectChanged -= handler;
        }

        /// <summary>
        /// subscription reconnect evnet.
        /// </summary>
        /// <param name="handler"></param>
        public void AddReConnectHandler(DeviceHandler handler)
        {
            ReConnectChanged += handler;
        }

        /// <summary>
        /// unsubscription reconnect event.
        /// </summary>
        /// <param name="handler"></param>
        public void RemoveReConnectHandler(DeviceHandler handler)
        {
            ReConnectChanged -= handler;
        }

        ~BaseDevice()
        {
            lock (ClientManager.InitLock)
            {
                if (ClientManager.ClientCount == 1)
                {
                    NETClient.Cleanup();
                }
                ClientManager.ClientCount--;
            }
        }

        /// <summary>
        /// call netsdk init function.and throw exception.
        /// </summary>
        private void Init()
        {
            try
            {
                bool res = NETClient.Init(m_disConnect, IntPtr.Zero, null);
                if (res == false)
                {
                    throw new Exception("NetDeviceClient init failed!");
                }
                NETClient.SetAutoReconnect(m_ReConnectCallBack, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }

        /// <summary>
        /// disconnect callback funtion.
        /// </summary>
        /// <param name="lLoginID">loginid</param>
        /// <param name="pchDVRIP">ip</param>
        /// <param name="nDVRPort">port</param>
        /// <param name="dwUser">user data</param>
        private void DisConnect(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            DeviceEventArgs disDev = new DeviceEventArgs(lLoginID, Marshal.PtrToStringAnsi(pchDVRIP), (ushort)nDVRPort, dwUser);
            this.Dispatcher.BeginInvoke((Action<object, DeviceEventArgs>)OnDisConnectChanged, lLoginID, disDev);
        }

        /// <summary>
        /// reconnect callback function.
        /// </summary>
        /// <param name="lLoginID">loginid</param>
        /// <param name="pchDVRIP">ip</param>
        /// <param name="nDVRPort">port</param>
        /// <param name="dwUser">user data</param>
        private void ReConnectCallBack(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            DeviceEventArgs disDev = new DeviceEventArgs(lLoginID, Marshal.PtrToStringAnsi(pchDVRIP), (ushort)nDVRPort, dwUser);
            this.Dispatcher.BeginInvoke((Action<object, DeviceEventArgs>)OnReConnectChanged, lLoginID, disDev);
        }
    }

    
}
