using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using TSDome.Receiver;
namespace TSDome
{
    public partial class Form1 : Form
    {
        private int m_bInitSDK = 0;
        private int m_lUserID = 0;
        private bool m_bP2P = false;
        private IntPtr m_hsHandle=IntPtr.Zero;
        private ushort m_PortNumber = 0;
        private int m_lRealHandle = -1;
        private int iLastErr = 0;
        private int m_curplaychannel;
        private int m_curplay_dechandle;
        private string str;
        private string m_filepath = "F:\\11.264";
        NetSDK.NET_SDK_DEVICEINFO m_DeviceInfo = new NetSDK.NET_SDK_DEVICEINFO();
        PlayBack dlg = new PlayBack();
        User dlguser = new User();
        //AlarmPush dlgAlarm = new AlarmPush();
        private NetSDK.fNetDisConnect m_ConnectData = null;
        private NetSDK.fNetRealDataCallBack m_RealData = null;
        private NetSDK.fNetMessCallBack m_MessData = null;
        Receiver.ReceiverServiceResponseClient client = new Receiver.ReceiverServiceResponseClient();
        public Form1()
        {
            InitializeComponent();
            string netsdkversion=GetVersionInfo("NetSdkModule.dll");
            string playsdkversion = GetVersionInfo("PlaySdkModule.dll");
            string Version="";
            if(netsdkversion!="")
            {
                Version = Version + " NetSDK:" + netsdkversion;
            }
            if(playsdkversion!="")
            {
                Version = Version + " PlaySDK:" + playsdkversion;
            }
            labelVision.Text = Version;
            comboBoxStream.Items.Insert(0,"Main Stream");
            comboBoxStream.Items.Insert(1,"Sub Stream");
            comboBoxStream.SelectedIndex = 0;
            buttonStopRecord.Enabled=false;
            m_ConnectData = new NetSDK.fNetDisConnect(DisConnectBackCallFunc);
            m_MessData = new NetSDK.fNetMessCallBack(CallbackAlarmInfo);
            m_bInitSDK = NetSDK.NET_SDK_Init(m_ConnectData,IntPtr.Zero);
            NetSDK.NET_SDK_SetDVRMessCallBack(m_MessData,IntPtr.Zero);
            NetSDK.NET_SDK_InitGlink("TSClient", "20141102", "1234567890", 101, 1);
            if(m_bInitSDK==0)
            {
                MessageBox.Show("NET_SDK_Init error!");
                return;
            }
            buttonAlarmPush.Hide();
        }

        public void DisConnectBackCallFunc(int lLoginID, string pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            /*断线回调*/
            /* disconnect callback*/
            MessageBox.Show("Device disconnection");
        }
        public  char CallbackAlarmInfo(int lLoginID, IntPtr pBuf, uint dwBufLen, IntPtr dwUser)
        {
            NetSDK.NET_SDK_AlarmInfo alarmInfo = (NetSDK.NET_SDK_AlarmInfo)Marshal.PtrToStructure(pBuf, typeof(NetSDK.NET_SDK_AlarmInfo));
            if(!checkBox1.Checked)
            {
                return '\0';
            }
            //外部报警 External alarm
            if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_NET_ALARM == alarmInfo.iEvent
                || (int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_MANUAL_ALARM == alarmInfo.iEvent
                || (int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_LOCAL_ALARM == alarmInfo.iEvent)
            {
                MessageBox.Show("External alarm");
            }
            else if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_VIDEO_MOTION == alarmInfo.iEvent)
            {
                MessageBox.Show("MOTION");
            }
            else if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_VIDEO_LOSS == alarmInfo.iEvent)
            {
                MessageBox.Show("VIDEO_LOSS");
            }
            else if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_VIDEO_BLIND == alarmInfo.iEvent)
            {
                MessageBox.Show("VIDEO_BLIND");
            }
            else if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_STORAGE_FAILURE == alarmInfo.iEvent)
            {
                MessageBox.Show("Storage failed (hard disk error)");
            }
            else if ((int)NetSDK.NET_SDK_EventCodeTypes.NET_SDK_EVENT_CODE_LOW_SPACE == alarmInfo.iEvent)
            {
                MessageBox.Show("Insufficient disk space (hard disk full)");
            }
            char breturn = '\0';
            return breturn;
        }
       public bool IsValidIP(string ip)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(ip,"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    if(System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                    return true;
                    else
                    return false;
                }
                else
                return false;
            }
            else
            return false;
        } 
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            if (textBoxIP.Text == "" || textBoxPort.Text == "" ||
                textBoxName.Text == "" )
            {
                MessageBox.Show("Please input IP, Port, User name and Password!");
                return;
            }
            Logout();
            string IPAddress = textBoxIP.Text; //设备IP地址或者域名 Device IP address or domain name
            ushort PortNumber = ushort.Parse(textBoxPort.Text);//设备服务端口号 Device service port number
            string UserName = textBoxName.Text;//设备登录用户名 Device login user name
            string Password = textBoxPassword.Text;//设备登录密码 Device login password
            string szTmp;
            if(!IsValidIP(IPAddress))
            {
                m_bP2P=true;
                ulong nTmp = GetHSP2PIPPort(IPAddress.ToCharArray(),ref PortNumber);
                if (nTmp > 0)
                {
                    //qDebug("GetHSP2PIPPort %s--%d--handle:%d\n", szIp, nTmpPort, nTmp);
                    return; //(nTmp == 1) ? 0 : nTmp;
                }
                m_PortNumber = PortNumber;
               szTmp="127.0.0.1";	
            }
            else
            {
                m_bP2P = false;
                szTmp = IPAddress;
            }
            int error=new int();
            m_lUserID = NetSDK.NET_SDK_Login(szTmp, PortNumber, UserName, Password, ref m_DeviceInfo, 0, ref error, 0, 0);
            if(m_lUserID>0)
            {
                NetSDK.NET_SDK_SetupAlarmChan(m_lUserID);
                MessageBox.Show("Login Success!");
                string strChannel = "Channel";
                for (int i = 0; i < (m_DeviceInfo.byChanNum + m_DeviceInfo.iDigChannel); i++)
                {
                    comboBoxChannel.Items.Insert(i, strChannel + (i + 1).ToString());
                    comboBoxChannel.SelectedIndex = 0;
                }
                labDeviceVersion.Text = "Device Version:" + new string( m_DeviceInfo.sSoftWareVersion);
            }
            else
            {
                MessageBox.Show("Login Failure!"+error.ToString());
            }
        }
        public ulong GetHSP2PIPPort(char[] szUID,ref ushort nPort)
        {
            if(m_hsHandle==IntPtr.Zero||AlarmSDK.NPC_F_MPI_MON_DNP_CheckSrvConnState(m_hsHandle) != 2)
	        {
                m_hsHandle = AlarmSDK.NPC_F_MPI_MON_DNP_CreateDevNetPortServer("123.207.228.156".ToCharArray(), 8300, "sdktest".ToCharArray(), "sdktest".ToCharArray(), 1);
		        if(m_hsHandle==IntPtr.Zero)
		        {
			        //qDebug()<<"m_hsHandle error"<<endl;
                    return 1;
		        }
	        }
            while(true)
	        {
                int n=AlarmSDK.NPC_F_MPI_MON_DNP_CheckSrvConnState(m_hsHandle) ;
                if(n==2)
                {
                    break;
                }
            }
	        ulong lRet = 0;	
		    ushort nTMpport = 0;
		    int nReturn = AlarmSDK.NPC_F_MPI_MON_DNP_AddPortByChNo(m_hsHandle,szUID,1,ref nTMpport,2000);
            if(nReturn==0)
		    {
			    nPort = nTMpport;
		    }
		    else
		    {
			//qDebug("nReturn error %d",nReturn);
			    lRet = 1;
		    }
        //printf("the port is :%d\n",tmpInfo.nPort);
	        return lRet;
        }
        private void buttonView_Click(object sender, EventArgs e)
        {
            int channel = comboBoxChannel.SelectedIndex;
            int stream = comboBoxStream.SelectedIndex;
            openView(channel, stream);
        }
        public void Logout()
        {
            if (m_lUserID > 0)
            {
                stopView();
                labDeviceVersion.Text = "";
                NetSDK.NET_SDK_Logout(m_lUserID);
                comboBoxChannel.Items.Clear();
                m_lUserID = -1;
                if(m_bP2P)
                {
                    AlarmSDK.NPC_F_MPI_MON_DNP_DelPort(m_hsHandle, m_PortNumber);
                }
            }
        }
        private void buttonLogout_Click(object sender, EventArgs e)
        {
            Logout();
        }
        public bool openView(int channel, int streamtype)
        {
            if (m_lUserID <= 0)
	        {
		        MessageBox.Show("Please first login the device");
		        return false;
	        }      
	        stopView();
	        int nPort = channel;
	        if (!(PlaySDK.PLAY_SDK_OpenStream(nPort, IntPtr.Zero, 1, 50*1024*150)==0))
	        {
		        if(!(PlaySDK.PLAY_SDK_Play(nPort,pictureBox1.Handle)==0))
		        {
			        m_curplaychannel = channel;
			        m_curplay_dechandle = nPort;
			        NetSDK.NET_SDK_CLIENTINFO client_info=new NetSDK.NET_SDK_CLIENTINFO();
			        client_info.nChannel = channel;
			        client_info.nStream = streamtype;
			        client_info.nMode = 0;
			        m_lRealHandle = NetSDK.NET_SDK_RealPlay(m_lUserID, ref client_info,0);
			        if (m_lRealHandle> 0)
			        {
                        m_RealData = new NetSDK.fNetRealDataCallBack(RealDataCallBack_TS);
				        NetSDK.NET_SDK_SetRealDataCallBack(m_lRealHandle,m_RealData,1);
				        return true;
			        }
			        else
			        {
				        int lerror = NetSDK.NET_SDK_GetLastError();
				        m_curplaychannel = 0;
				        m_curplay_dechandle = -1;
				        PlaySDK.PLAY_SDK_Stop(nPort);
				        PlaySDK.PLAY_SDK_CloseStream(nPort);
			        }	
		        }
		        else
		        {
			        PlaySDK.PLAY_SDK_CloseStream(nPort);
		        }
	        }
            return false;
        }
        public int RealDataCallBack_TS(int lRealHandle, int dwDataType, IntPtr pBuffer, int dwBufSize, IntPtr pUser)
        {
            PlaySDK.PLAY_SDK_InputData(m_curplay_dechandle, pBuffer, dwBufSize);	
	        return 1;
        }

        public void stopView()
        {
            if (m_lUserID<= 0 || m_lRealHandle <= 0)
            {
                return;
            }
            if(buttonStopRecord.Enabled)
            {
                stopRecord();
            }
            NetSDK.NET_SDK_DelRealDataCallBack(m_lRealHandle, m_RealData, 1);
            NetSDK.NET_SDK_StopRealPlay(m_lRealHandle);
            System.Diagnostics.Debug.WriteLine("ab");
            m_lRealHandle = 0;

            if (m_curplay_dechandle >= 0)
            {/*
                if (m_isRecording)
                {
                    PLAY_SDK_StopDataRecord(m_curplay_dechandle);
                    m_isRecording = false;
                }
                if (m_isSoundOpened)
                {
                    PLAY_SDK_StopSoundShare(m_curplay_dechandle);
                    m_isSoundOpened = false;
                }*/
               int c=PlaySDK.PLAY_SDK_Stop(m_curplay_dechandle);
               int d=PlaySDK.PLAY_SDK_CloseStream(m_curplay_dechandle);
               PlaySDK.PLAY_SDK_FreePort(m_curplay_dechandle);
               System.Diagnostics.Debug.WriteLine("cd");
               System.Diagnostics.Debug.WriteLine(c.ToString() + d.ToString());
               m_curplay_dechandle = -1;
            }
            pictureBox1.Invalidate();//刷新窗口 refresh the window
        }

        private void buttonStopView_Click(object sender, EventArgs e)
        {
            stopView();
        }


        private void buttonPlayBack_Click(object sender, EventArgs e)
        {
            if (m_lUserID > 0)
            {
                dlg.m_lUserID = m_lUserID;
                dlg.m_DeviceInfo = m_DeviceInfo;
                dlg.m_path = textBoxFile.Text;
                dlg.Init();
                dlg.Show();
            }
            else
            {
                MessageBox.Show("Please first login the device");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(m_curplay_dechandle>=0)
            {
                string filename = textBoxFile.Text + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString()
                    + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".jpg";
                int bRet = PlaySDK.PLAY_SDK_CatchPic(m_curplay_dechandle, filename,0);
                if(bRet>0)
                {
                    MessageBox.Show("Successful capture");
                }
                else
                {
                    MessageBox.Show("Failed to capture the map");
                }
            }
        }

        private void buttonStartRecord_Click(object sender, EventArgs e)
        {
            if(m_curplay_dechandle>=0)
            {
                string filename = textBoxFile.Text + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
                    + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".h264";
                int bRet = PlaySDK.PLAY_SDK_StartDataRecord(m_curplay_dechandle, filename, 0);
                if(bRet>0)
                {
                    buttonStartRecord.Enabled = false;
                    buttonStopRecord.Enabled = true;
                }
            }
        }

        private void buttonStopRecord_Click(object sender, EventArgs e)
        {
            stopRecord();
        }
        public void stopRecord()
        {
            if (m_lUserID <= 0 || m_curplay_dechandle < 0)
            {
                return;
            }
            buttonStartRecord.Enabled = true;
            buttonStopRecord.Enabled = false;
            PlaySDK.PLAY_SDK_StopDataRecord(m_curplay_dechandle);
        }

        private void buttonTime_Click(object sender, EventArgs e)
        {
            NetSDK.NET_SDK_SYSTEM_TIME sysTime=new NetSDK.NET_SDK_SYSTEM_TIME();
            sysTime.year=DateTime.Now.Year;
            sysTime.month=DateTime.Now.Month;
            sysTime.day=DateTime.Now.Day;
            sysTime.hour=DateTime.Now.Hour;
            sysTime.minute=DateTime.Now.Minute;
            sysTime.second=DateTime.Now.Second;
            sysTime.isdst = 0;
            IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NetSDK.NET_SDK_SYSTEM_TIME)));
            Marshal.StructureToPtr(sysTime, pt, false); 
            int nRet = NetSDK.NET_SDK_SetDevConfig(m_lUserID,(uint)NetSDK.NET_SDK_CONFIG_TYPE.NET_SDK_CONFIG_SYS_TIME,-1,pt,Marshal.SizeOf(typeof(NetSDK.NET_SDK_SYSTEM_TIME)),2000);
            if(nRet>0)
            {
                MessageBox.Show("Synchronization time is successful");
            }
        }

        private void buttonUser_Click(object sender, EventArgs e)
        {
            if (m_lUserID > 0)
            {
                dlguser.m_lUserID = m_lUserID;
                dlguser.update();
                dlguser.ShowDialog();
            }
            else
            {
                MessageBox.Show("Please first login the device");
            }
        }
        public string GetVersionInfo(string filePath)
        {
            string curVer = "";
            FileVersionInfo fv = FileVersionInfo.GetVersionInfo(filePath);
            curVer = fv.FileVersion;
            return curVer;
        }

        private void buttonAlarmPush_Click(object sender, EventArgs e)
        {
           // dlgAlarm.Show();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
           // dlgAlarm.DeleteAlarm();
            if(m_hsHandle!=IntPtr.Zero)
            {
                AlarmSDK.NPC_F_MPI_MON_DNP_DestroyDevNetPortServer(m_hsHandle);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBoxjosn.Text;
            //client.SendHeartBeat(str);
            string strret = client.SendAlarm(str);
            MessageBox.Show(strret);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string str = textBoxjosn.Text;
            //client.SendHeartBeat(str);
            string strret = client.SendHeartBeat(str);
            MessageBox.Show(strret);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string str = textBoxjosn.Text;
            //client.SendHeartBeat(str);
            string strret = client.GetNTPServerInfo(str);
            MessageBox.Show(strret);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string str = textBoxjosn.Text;
            //client.SendHeartBeat(str);
            string strret = client.SendRecorderInfo(str);
            MessageBox.Show(strret);
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxChannel_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
