using System;
using System.Collections;
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;
using System.Text.RegularExpressions;

namespace GcDevicePc
{
    public delegate void ChangeMainShow(object sender, EventArgs e);

    public partial class ListViewTest : Form
    {
        public event ChangeMainShow MainBase_Load;

       public UdpClient client;
       public IPEndPoint endpoint;
       public TreeNode rootnode;//= new TreeNode(); //创建根节点
       ManualResetEvent mre = new ManualResetEvent(false);

       Thread th;

       int nodeno;

       public delegate void invokeDelegate();
        
        //设备信息结构体
        public struct stWUEthInfo
        {
	       public byte[] byteMacAddr;
           public byte[] byteIpAddr;
           public byte[] byteNetmask;
           public byte[] byteGateway;
           public bool bActive;
        };

       //声明一个设备
       public stWUEthInfo m_pWUEthInfo;

       //定义设备信息存储容器
     //  public ArrayList gcList = null;

        public ListViewTest()
        {
            InitializeComponent();
        //    gcList = new ArrayList();
            m_pWUEthInfo.byteMacAddr = new byte[6];
            m_pWUEthInfo.byteIpAddr = new byte[4];
            m_pWUEthInfo.byteNetmask = new byte[4];
            m_pWUEthInfo.byteGateway = new byte[4];
           
            this.search.Enabled = true;
            this.button1.Enabled = false;

            //this.textBox1.Enabled = false;
            //this.textBox2.Enabled = false;
            //this.textBox3.Enabled = false;
          
        }

        private void search_Click(object sender, EventArgs e)
        {
          //  gcList.Clear();
            globaldata.DeviceList.Clear();
            treeView1.Nodes.Clear();
            CreateRootNodes(treeView1,"系统设备");
            this.search.Enabled = false;
            this.button1.Enabled = true;
            th = new Thread(ThreadMethod);
            th.IsBackground = true;
            th.Start();
        }

        private void ThreadMethod()
        {
            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);
                       //  break;
                }                                                      
            }  
        }

        public Boolean DoRecvDataCallBack( byte[] pcData, int iRecvLength)
        {
            Console.WriteLine("DoRecvDataCallBack中。。。");
            byte[] pBuf = pcData;
            int iDataLength = 0;

            ArrayList gcname = new ArrayList();
            //string wtModuleName;

            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))
                {
                    // 获取模块名称
                    //StringBuilder sb=new StringBuilder();
                    //sb.Append(Convert.ToChar(pBuf[6]));
                    //sb.Append(Convert.ToChar(pBuf[7]));
                    //sb.Append(Convert.ToChar(pBuf[8]));
                    //sb.Append(Convert.ToChar(pBuf[9]));
                    //wtModuleName = sb.ToString();
                    //sb.Length = 0; //清空

                    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]);
                   
		
			        // 新建一个以太网设备信息
                    //m_pWUEthInfo.bActive = false;
			        
                    //m_pWUEthInfo.byteMacAddr[0] = pBuf[10];
                    //m_pWUEthInfo.byteMacAddr[1] = pBuf[11];
                    //m_pWUEthInfo.byteMacAddr[2] = pBuf[12];
                    //m_pWUEthInfo.byteMacAddr[3] = pBuf[13];
                    //m_pWUEthInfo.byteMacAddr[4] = pBuf[14];
                    //m_pWUEthInfo.byteMacAddr[5] = pBuf[15];

                    //m_pWUEthInfo.byteIpAddr[0] = pBuf[16];
                    //m_pWUEthInfo.byteIpAddr[1] = pBuf[17];
                    //m_pWUEthInfo.byteIpAddr[2] = pBuf[18];
                    //m_pWUEthInfo.byteIpAddr[3] = pBuf[19];

                    //m_pWUEthInfo.byteNetmask[0] = pBuf[20];
                    //m_pWUEthInfo.byteNetmask[1] = pBuf[21];
                    //m_pWUEthInfo.byteNetmask[2] = pBuf[22];
                    //m_pWUEthInfo.byteNetmask[3] = pBuf[23];

                    //m_pWUEthInfo.byteGateway[0] = pBuf[24];
                    //m_pWUEthInfo.byteGateway[1] = pBuf[25];
                    //m_pWUEthInfo.byteGateway[2] = pBuf[26];
                    //m_pWUEthInfo.byteGateway[3] = pBuf[27];

                   // globaldata.DeviceList.Add(globaldata.m_DeviceInfo);

                    int onenode = treeView1.Nodes[0].GetNodeCount(false);
                    Console.WriteLine("onenode is" + onenode.ToString());

                    gcname.Clear();

                    if (onenode == 0)
                    {
                        gcname.Add(globaldata.m_DeviceInfo.ModuleName);
                    }
                    else
                    {
                        for (int i = 0; i < onenode; i++)
                        {
                            gcname.Add(treeView1.Nodes[0].Nodes[i].Text);
                        }
                    }

                    int myno = StrInArray(globaldata.m_DeviceInfo.ModuleName, gcname);
                    int gcno;
                             
                    invokeDelegate update_treeview = () =>
                    {
                        int nodes;
                        if (myno >= 0)
                        {
                            nodes = treeView1.Nodes[0].GetNodeCount(false);
                            Console.WriteLine("nodes is " + nodes.ToString());

                            if (nodes == 0)
                            {
                                CreateChildNodes(treeView1.Nodes[0], globaldata.m_DeviceInfo.ModuleName);
                                CreateChildNodes(treeView1.Nodes[0].Nodes[nodes], (nodes + 1).ToString());
                                treeView1.Nodes[0].Expand();
                                treeView1.Nodes[0].Nodes[nodes].Expand();
                            }
                            else
                            {
                                gcno = treeView1.Nodes[0].Nodes[nodes - 1].GetNodeCount(false);
                                CreateChildNodes(treeView1.Nodes[0].Nodes[nodes - 1], (gcno + 1).ToString());
                                treeView1.Nodes[0].Expand();
                                treeView1.Nodes[0].Nodes[nodes - 1].Expand();

                            }                            
                        }
                        else
                        {
                            CreateChildNodes(treeView1.Nodes[0], globaldata.m_DeviceInfo.ModuleName);
                            nodes = treeView1.Nodes[0].GetNodeCount(false);                          
                            CreateChildNodes(treeView1.Nodes[0].Nodes[nodes-1], "1");
                            treeView1.Nodes[0].Expand();
                            treeView1.Nodes[0].Nodes[nodes - 1].Expand();
                        }
                    };
                    Invoke(update_treeview);

                    //这里由于只有一类设备，存储按相关顺序！！！！！！！！！！！！
                  //  gcList.Add(m_pWUEthInfo);
                    globaldata.DeviceList.Add(globaldata.m_DeviceInfo);
                  //  Console.WriteLine("nodes is " + gcList.Count.ToString());
                    return true;
                }
            }
            return false;
        }

        public static int StrInArray(string str, ArrayList strarry)
        {
            if (str == null)
                return -1;
            if (strarry == null || strarry.Count == 0)
                return -1;

            for (int i = 0; i < strarry.Count; i++)
            {
                if (strarry[i].ToString() == null)
                    continue;
                if (str == strarry[i].ToString())
                    return i;
            }

            return -1;
        }

        public void ListViewTest_Load(object sender, EventArgs e)
        {
            TreeNode rootnode = new TreeNode();
            rootnode.Text =  "系统设备";
            treeView1.Nodes.Add(rootnode);
        }


        public void CreateRootNodes(TreeView treeview,string text)
        {
            TreeNode rootnode = new TreeNode();
            rootnode.Text = text;
            treeview.Nodes.Add(rootnode);
        }

        public void CreateChildNodes(TreeNode treenode,string text)
        {
            TreeNode childnode = new TreeNode();
            childnode.Text = text;
            treenode.Nodes.Add(childnode);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            mre.Set();
            this.search.Enabled = true;
            this.button1.Enabled = false;    
            Console.WriteLine("信号发送...");
        
            Thread.Sleep(1000);
     //       th.Abort();
            mre.Reset();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string text1;
            
            string strIP, strGW, strMask;
           // StringBuilder sb;
        //    stWUEthInfo tmp;
            if ( globaldata.DeviceList.Count > 0)
            {
                text1 = treeView1.SelectedNode.Text;
                this.label1.Text = "设备 " + text1;
               // if (Regex.IsMatch(text1, @"^/d*[.]?/d*$"))
                    nodeno = Convert.ToInt32(text1);
               // else
                 //   nodeno = 1;

              //  nodeno = Convert.ToInt32(text1);

              //  tmp = (stWUEthInfo)gcList[nodeno - 1];        
               // strIP = String.Format("{0}.{1}.{2}.{3}", tmp.byteIpAddr[0],tmp.byteIpAddr[1],tmp.byteIpAddr[2],tmp.byteIpAddr[3]);
                strIP = ((globaldata.DeviceInfo)globaldata.DeviceList[nodeno - 1]).IpAddr;
                   // ((globaldata.DeviceInfo)globaldata.DeviceList[i])
                this.textBox1.Text = strIP;

               // strGW = String.Format("{0}.{1}.{2}.{3}", tmp.byteGateway[0], tmp.byteGateway[1], tmp.byteGateway[2], tmp.byteGateway[3]);
                strGW = ((globaldata.DeviceInfo)globaldata.DeviceList[nodeno - 1]).Gateway;
                this.textBox2.Text = strGW;

               // strMask = String.Format("{0}.{1}.{2}.{3}", tmp.byteNetmask[0], tmp.byteNetmask[1], tmp.byteNetmask[2], tmp.byteNetmask[3]);
                strMask = ((globaldata.DeviceInfo)globaldata.DeviceList[nodeno - 1]).Netmask;
                this.textBox3.Text = strMask;

                string sMac = ((globaldata.DeviceInfo)globaldata.DeviceList[nodeno - 1]).MacAddr;
                string[] p = sMac.Split(':');
                byte[] mac = new byte[6];
                for (int i = 0; i < 6; i++ )
                {
                    mac[i] = Convert.ToByte(p[i]);
                    m_pWUEthInfo.byteMacAddr[i] = mac[i];
                }    
            }   
        }

     
        public void changeset_Click(object sender, EventArgs e)
        {
          

            byte[] headBytes = new byte[] { 0x57, 0x54, 0x14, 0x00, 0x00, 0x00, 0x06, 0x00 };
            byte[] endBytes = new byte[] { 0x55, 0xAA };

            string myIP;
            string myMask;
            string myGW;
            myIP = this.textBox1.Text;
            myGW = this.textBox2.Text;
            myMask = this.textBox3.Text;
            
            int i = 0;

            byte [] sMac = new byte[6];

           sMac[0] = m_pWUEthInfo.byteMacAddr[0];
           sMac[1] = m_pWUEthInfo.byteMacAddr[1];
           sMac[2] = m_pWUEthInfo.byteMacAddr[2];
           sMac[3] = m_pWUEthInfo.byteMacAddr[3];
           sMac[4] = m_pWUEthInfo.byteMacAddr[4];
           sMac[5] = m_pWUEthInfo.byteMacAddr[5];

            byte [] update = new byte[12];

            string[] sIP = myIP.Split('.');      
            for (i = 0; i < 4; i++)
                update[i] = Convert.ToByte(sIP[i]);


            string[] sMask = myMask.Split('.');
            for (i = 0; i < 4; i++)
                update[i + 4] = Convert.ToByte(sMask[i]);

            string[] sGW = myGW.Split('.');
            for (i = 0; i < 4; i++)
                update[i + 8] = Convert.ToByte(sGW[i]);
               
            byte[] sendBytes = new Byte[headBytes.Length + sMac.Length + update.Length + endBytes.Length ];
            headBytes.CopyTo(sendBytes,0);
            sMac.CopyTo(sendBytes, headBytes.Length);
            update.CopyTo(sendBytes, headBytes.Length + sMac.Length);
            endBytes.CopyTo(sendBytes, headBytes.Length + sMac.Length + update.Length);

            client.Send(sendBytes, sendBytes.Length, endpoint);

        }

        private void switch_device_Click(object sender, EventArgs e)
        {
            if (this.nodeno >= 1)
            {
                globaldata.current_device = nodeno -1;
                globaldata.connection_ip = ((globaldata.DeviceInfo)globaldata.DeviceList[globaldata.current_device]).IpAddr;
            }
            
            MainBase_Load(sender, e);
            this.Hide();
        }
    }
}
