using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;

using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace GcDevicePc
{
    public partial class SearchDevices : Form
    {
        public UdpClient client;
        public IPEndPoint endpoint;
        public Thread searchth;
        ManualResetEvent mre = new ManualResetEvent(false);
        public delegate void invokeDelegate();

        public int devicenum;

        ToolTip toolTip1 = new ToolTip();
        public SearchDevices()
        {
            InitializeComponent();
           
            toolTip1.AutoPopDelay = 5000;
            toolTip1.InitialDelay = 300;
            toolTip1.ReshowDelay = 200;
            toolTip1.ShowAlways = true;

            //toolTip1.SetToolTip(this.button1, "点击后自动生成条码");
            //toolTip1.SetToolTip(this.button2, "悬停提示的内容");
        }

        private void SearchDevices_Load(object sender, EventArgs e)
        {          
            this.searchbtn.Text = "搜索";

            if (this.searchbtn.Text == "重新搜索" || this.searchbtn.Text == "搜索")
            {
                localrun.Enabled = false;
                this.searchbtn.Text = "搜索停止";
                this.sinfo.Text = "设备搜索中(停止可选择设备)";
                this.sinfo.ForeColor = Color.Red;
                this.searchPanel.Controls.Clear();
                CreateSearchThread();
                globaldata.DeviceList.Clear();
            }            
        }

        private void CreateSearchThread()
        {
            this.devicenum = 0;
            searchth = new Thread(SearchThreadMethod);
            searchth.IsBackground = true;
            searchth.Start();
        }

        private void SearchThreadMethod(object obj)
        {
            byte[] sendBytes = new byte[] { 0x57, 0x54, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x55, 0xAA };
            int iReadBytes = 0;

            client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
            endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 233);

            client.Send(sendBytes, sendBytes.Length, endpoint);
            Thread.Sleep(1000);

            byte[] recvBytes;
            client.Client.Blocking = false;
            while (!mre.WaitOne(500))
            {
                iReadBytes = 30;

                int buffSizeCurrent;
                buffSizeCurrent = client.Client.Available;

                if (buffSizeCurrent > 0)
                {
                    recvBytes = client.Receive(ref endpoint);
                    iReadBytes = recvBytes.Length;
                  //  Console.WriteLine(iReadBytes.ToString());
                    DoRecvDataCallBack(recvBytes, iReadBytes);
                }
            }
            Console.WriteLine("线程结束!");
        }

        private Boolean DoRecvDataCallBack(byte[] pcData, int iRecvLength)
        {   
            byte[] pBuf = pcData;
            int iDataLength = 0;
     
            if (iRecvLength < 8)
                return false;

            if ((pBuf[0] == (byte)0x57) && (pBuf[1] == (byte)0x54) && (pBuf[iRecvLength - 2] == (byte)0x55) && (pBuf[iRecvLength - 1] == (byte)0xAA))
            {
                iDataLength = (int)(pBuf[2] & 0xFF)
                                | (int)((pBuf[3] & 0xFF) << 8)
                                | (int)((pBuf[4] & 0xFF) << 16)
                                | (int)((pBuf[5] & 0xFF) << 24);


                if ((iDataLength >= 4) && (iRecvLength == 8 + iDataLength))
                {                                
                    // 新建一个以太网设备信息
                    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                    globaldata.m_DeviceInfo.bActive = false;
                    globaldata.m_DeviceInfo.ModuleName = String.Format("{0}{1}{2}{3}",asciiEncoding.GetString(pBuf,6,1),
                                                                                      asciiEncoding.GetString(pBuf,7,1),
                                                                                        asciiEncoding.GetString(pBuf,8,1),
                                                                                        asciiEncoding.GetString(pBuf,9,1));
                    globaldata.m_DeviceInfo.MacAddr = String.Format("{0}:{1}:{2}:{3}:{4}:{5}", pBuf[10],pBuf[11],pBuf[12],pBuf[13],pBuf[14],pBuf[15]);
                    globaldata.m_DeviceInfo.IpAddr = String.Format("{0}.{1}.{2}.{3}", pBuf[16],pBuf[17],pBuf[18],pBuf[19]);
                    globaldata.m_DeviceInfo.Netmask =  String.Format("{0}.{1}.{2}.{3}", pBuf[20],pBuf[21],pBuf[22],pBuf[23]);
                    globaldata.m_DeviceInfo.Gateway = String.Format("{0}.{1}.{2}.{3}", pBuf[24], pBuf[25], pBuf[26], pBuf[27]);
                   
                    if(globaldata.m_DeviceInfo.IpAddr != "0.0.0.0")
                    {
                        invokeDelegate update_tablepanel = () =>
                        {
                            PictureBox devicetag = new PictureBox();
                            devicetag.Padding = devicetag.Margin = new Padding(0);
                            devicetag.Name = devicenum.ToString();
                            devicetag.Width = 122;
                            devicetag.Height = 80;
                            devicetag.Dock = DockStyle.None;
                            devicetag.Enabled = false;
                            devicetag.Image = searchimage.Images[0];
                            devicetag.BackgroundImageLayout = ImageLayout.Stretch;
                            devicetag.Click += new EventHandler(devicetag_Click);
                            devicetag.MouseHover += new EventHandler(devicetag_MouseHover);
                            devicetag.MouseLeave += new EventHandler(devicetag_MouseLeave);

                            this.toolTip1.SetToolTip(devicetag, "设备IP:" + globaldata.m_DeviceInfo.IpAddr.ToString());
                            //Label devicename = new Label();
                            //devicename.Width = 30;
                            //devicename.Height = 10;
                            //devicename.Dock = DockStyle.None;

                            //devicename.Text = "112";

                            //Panel onetag = new Panel();
                            //onetag.Controls.Add(devicetag);
                            //onetag.Controls.Add(devicename);
                            //onetag.Width = 122;
                            //onetag.Height = 80;
                            //onetag.Dock = DockStyle.None;
                           
                            if (this.devicenum >= 4)
                            {
                               // this.searchPanel.Controls.Add(onetag, devicenum % 4, 0);
                                this.searchPanel.Controls.Add(devicetag, (devicenum - 4) % 4, 1);
                              //  this.searchPanel.Controls.Add(devicename, (devicenum - 4) % 4, 1);
                            }                                
                            else
                            {
                              //  this.searchPanel.Controls.Add(onetag, devicenum % 4, 0);
                                this.searchPanel.Controls.Add(devicetag, devicenum % 4, 0);
                              //  this.searchPanel.Controls.Add(devicename, devicenum % 4, 0);
                            }
                                

                        };
                        Invoke(update_tablepanel);

                        //这里由于只有一类设备，存储按相关顺序！！！！！！！！！！！！
                        globaldata.DeviceList.Add(globaldata.m_DeviceInfo);
                        this.devicenum += 1;
                        return true;
                    }                                 
                }
            }
            return false;
        }

        private void devicetag_MouseLeave(object sender, EventArgs e)
        {
            PictureBox pVideo = (PictureBox)sender;
            pVideo.Image = searchimage.Images[0];
        }

        private void devicetag_MouseHover(object sender, EventArgs e)
        {
            PictureBox pVideo = (PictureBox)sender;
            pVideo.Image = searchimage.Images[1];    
        }

        //跳转函数
        private void devicetag_Click(object sender, EventArgs e)
        {
            PictureBox pVideo = (PictureBox)sender;
           

            globaldata.current_device = Convert.ToInt32(pVideo.Name);
            globaldata.connection_ip = ((globaldata.DeviceInfo)globaldata.DeviceList[globaldata.current_device]).IpAddr;

            this.Hide();
            MainForm mainfrom = new MainForm();
            mainfrom.Show();
        }

        private void searchbtn_Click(object sender, EventArgs e)
        {
            if (this.searchbtn.Text == "重新搜索" || this.searchbtn.Text == "搜索")
            {
                localrun.Enabled = false;
                this.searchbtn.Text = "搜索停止";
                this.sinfo.Text = "设备搜索中(停止可选择设备)";
                this.sinfo.ForeColor = Color.Red;
                this.searchPanel.Controls.Clear();
                CreateSearchThread();
               
                globaldata.DeviceList.Clear();
            }
            else if (this.searchbtn.Text == "搜索停止")
            {
                localrun.Enabled = true;
                this.sinfo.Text = "";
                this.sinfo.ForeColor = Color.Red;
                foreach (Control ctr in this.searchPanel.Controls)
                {                   
                        ctr.Enabled = true;
                }

                mre.Set();              
                Console.WriteLine("信号发送...");
                Thread.Sleep(500);
                this.searchbtn.Text = "重新搜索";

        //        this.searchth.Suspend();

                mre.Reset();
            }else
            {
                Console.WriteLine("什么都不是");
            }
        }

        private void localrun_Click(object sender, EventArgs e)
        {
            mre.Set();
            Thread.Sleep(500);
            mre.Reset();
            globaldata.current_device = 0;
            MainForm mainfrom = new MainForm();
           // mainfrom.fatherForm = this;
            mainfrom.Show();
            this.Hide();
        }
    }
}
