using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QLightRFLibrary;

namespace QLightRFLibraryExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            QLightAPI.SetRouterStatusEventHandler(new RouterStatusEventHandler(routerStatusEventHandler));

            LEDState state = LEDState.OFF;
            SetLEDButton("Red", state); 
            SetLEDButton("Orange", state);
            SetLEDButton("Green", state);
            SetLEDButton("Blue", state);
            SetLEDButton("White", state);

            textBox3.Text = QLightAPI.GetScanInterval().ToString();
            textBox4.Text = QLightAPI.GetTTL().ToString();
            textBox5.Text = QLightAPI.GetSendNumber().ToString();
            ScanMethod m = QLightAPI.GetScanMethod();
            if (m == ScanMethod.ALL) comboBox6.SelectedItem = "ALL";
            else if (m == ScanMethod.GROUP) comboBox6.SelectedItem = "GROUP";
        }

        private void routerStatusEventHandler(ushort nodeId, RouterStatus status)
        {
            var list = QLightAPI.GetAllRouterList();
            RefreshRouterList(list);
            PrintMessage(String.Format("[new Router Status.] nodeId:{0} - Red:{1}, Orange:{2}, Green:{3}, Blue:{4}, White:{5}, Sound:{6}", 
                nodeId, status.Red, status.Orange, status.Green, status.Blue, status.White, status.SoundNumber));
        }

        private delegate void RefreshRouterListDelegate(Dictionary<ushort, ushort> list);
        private void RefreshRouterList(Dictionary<ushort,ushort> list)
        {
            if(this.InvokeRequired)
            {
                var d = new RefreshRouterListDelegate(RefreshRouterList);
                BeginInvoke(d, new object[] { list });
            }
            else
            {
                string selectedItem = "";
                if (comboBox2.SelectedIndex >= 0)
                {
                    selectedItem = comboBox2.SelectedItem as string;
                }
                comboBox2.Items.Clear();
                comboBox3.Items.Clear();
                if (list.Count == 0) return;
                List<string> strs = new List<string>();
                //ushort[] nodeIds = new ushort[list.Keys.Count];
                foreach(ushort nodeId in list.Keys)
                {
                    if (list.TryGetValue(nodeId, out ushort groupId))
                    {
                        strs.Add(String.Format("{0}-{1}", nodeId, groupId));
                    }
                }
                
                comboBox2.Items.AddRange(strs.ToArray());
                comboBox3.Items.AddRange(strs.ToArray());

                textBox1.Text = "";
                textBox2.Text = "";
                if(selectedItem != "" && comboBox2.Items.Contains(selectedItem)) comboBox2.SelectedItem = selectedItem;
                RefreshRouterCount();
            }
        }

        private delegate void ClearRouterListDelegate();
        private void ClearRouterList()
        {
            if (this.InvokeRequired)
            {
                var d = new ClearRouterListDelegate(ClearRouterList);
                BeginInvoke(d, null);
            }
            else
            {
                string selectedItem = "";

                if (comboBox2.SelectedIndex >= 0)
                {
                    selectedItem = comboBox2.SelectedItem as string;
                }
                var list = QLightAPI.GetAllRouterList();
                comboBox2.Items.Clear();
                comboBox3.Items.Clear();
                List<string> strs = new List<string>();
                ushort[] nodeIds = list.Keys.ToArray();
                for (int i = 0; i < nodeIds.Length; i++)
                {
                    ushort nodeId = nodeIds[i];
                    if (list.TryGetValue(nodeId, out ushort groupId))
                    {
                        QLightAPI.DeleteRouterList(nodeId);
                    }
                }
                textBox1.Text = "";
                textBox2.Text = "";

                if (selectedItem != "" && comboBox2.Items.Contains(selectedItem)) comboBox2.SelectedItem = selectedItem;
                RefreshRouterCount();
            }

        }

        private delegate void RefreshRouterCountDelegate();
        private void RefreshRouterCount()
        {
            if (this.InvokeRequired)
            {
                var d = new RefreshRouterCountDelegate(RefreshRouterCount);
                BeginInvoke(d, null);
            }
            else
            {
                label25.Text = String.Format("Router Count:{0}", comboBox2.Items.Count);
            }
        }

        private delegate void RefreshRouterStatusDelegate(RouterStatus status);
        private void RefreshRouterStatus(RouterStatus status)
        {
            if (this.InvokeRequired)
            {
                var d = new RefreshRouterStatusDelegate(RefreshRouterStatus);
                BeginInvoke(d, new object[] { status });
            }
            else
            {
                SetLEDButton("Red", status.Red); controlLedState[0] = status.Red;
                SetLEDButton("Orange", status.Orange); controlLedState[1] = status.Orange;
                SetLEDButton("Green", status.Green); controlLedState[2] = status.Green;
                SetLEDButton("Blue", status.Blue); controlLedState[3] = status.Blue;
                SetLEDButton("White", status.White); controlLedState[4] = status.White;

                SetSoundButton(status.SoundNumber);
            }

        }

        private delegate void RefreshRouterInfoDelegate(RouterInfo info);
        private void RefreshRouterInfo(RouterInfo info)
        {
            if (this.InvokeRequired)
            {
                var d = new RefreshRouterInfoDelegate(RefreshRouterInfo);
                BeginInvoke(d, new object[] { info });
            }
            else
            {
                lbNodeId.Text = info.NodeId.ToString();
                lbName.Text = (info.Name == "" || info.Name==null) ? "(none)":info.Name;
                lbGroupId.Text = info.GroupId.ToString();
            }
        }

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabControl tc = (TabControl)sender;
            switch(tc.SelectedIndex)
            {
                case 0:
                    button1.PerformClick();
                    //if (button7.Enabled) button7.PerformClick();
                    //if (button15.Enabled) button5.PerformClick();
                    break;
                case 1:
                    button1.PerformClick();
                    //if (button3.Enabled) button3.PerformClick();
                    //if (button15.Enabled) button15.PerformClick();
                    break;
                case 2:
                    button17.PerformClick();
                    //if (button3.Enabled) button3.PerformClick();
                    //if (button7.Enabled) button7.PerformClick();
                    break;
                default: break;
            }
            
            //QLightAPI.DisconnectAndClearAllConnection();
        }

        private delegate void PrintMessageDelegate(string msg);
        private void PrintMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                var d = new PrintMessageDelegate(PrintMessage);
                BeginInvoke(d, new object[] { msg });
            }
            else
            {
                string[] msgArr = msg.Split('\n');
                foreach(string m in msgArr)
                {
                    listBox1.Items.Add(m);
                }
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.SelectedIndex = -1;
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            string[] portList = SerialPort.GetPortNames();
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(portList);
            comboBox1.Refresh();

            comboBox4.Items.Clear();
            comboBox4.Items.AddRange(portList);
            comboBox4.Refresh();

            if (comboBox1.Items.Count == 1) comboBox1.SelectedIndex = 0;
            if (comboBox4.Items.Count == 1) comboBox4.SelectedIndex = 0;
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1) return;
            if(QLightAPI.ConnectUSBDongle(comboBox1.Text))
            {
                PrintMessage("[USB Dongle] Connected to " + comboBox1.Text);
                button2.Enabled = false;
                button3.Enabled = true;
                button4.Enabled = true;
            }
            else
            {
                PrintMessage("[USB Dongle] Fail to connect to " + comboBox1.Text);
            }
            if (QLightAPI.GetConnectedControllerList() != null)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            if (QLightAPI.GetConnectStatusUSBDongle(comboBox1.Text)) QLightAPI.DisconnectUSBDongle(comboBox1.Text);
            PrintMessage("[USB Dongle] Disconnected from " + comboBox1.Text);
            button2.Enabled = true;
            button3.Enabled = false;
            button4.Enabled = false;
            if (QLightAPI.GetConnectedControllerList() != null)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
            var list = QLightAPI.GetAllRouterList();
            RefreshRouterList(list);
        }

        private async void Button4_Click(object sender, EventArgs e)
        {
            USBDongleInfo info = await QLightAPI.GetInfoUSBDongle(comboBox1.Text);

            if (info.PortName == "")
            {
                PrintMessage("[USB Dongle] Get Info - null");
            }
            else
            {
                string msg = String.Format("[USB Dongle] Get Info - portName:{0}, dongleId:{1}, name:{2}, groupId:{3}, channel:{4}, panId:{5}, txPower:{6}",
                    info.PortName, info.DongleId, info.Name, info.GroupId, info.Channel, info.PandId, info.TxPower);
                PrintMessage(msg);
            }
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            if (QLightAPI.GetConnectStatusGatewayUSB(comboBox4.Text)) QLightAPI.DisconnectGatewayUSB(comboBox4.Text);
            PrintMessage("[GW USB] Disconnected from " + comboBox4.Text);
            button10.Enabled = true;
            button13.Enabled = false;
            button7.Enabled = false;
            if (QLightAPI.GetConnectedControllerList() != null)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
            var list = QLightAPI.GetAllRouterList();
            RefreshRouterList(list);
        }

        private void Button15_Click(object sender, EventArgs e)
        {
            if (QLightAPI.GetConnectStatusGatewayLAN(comboBox5.Text)) QLightAPI.DisconnectGatewayLAN(comboBox5.Text);
            PrintMessage("[GW LAN] Disconnected from " + comboBox5.Text);
            button16.Enabled = true;
            button14.Enabled = false;
            button15.Enabled = false;
            if (QLightAPI.GetConnectedControllerList() != null)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
            var list = QLightAPI.GetAllRouterList();
            RefreshRouterList(list);
        }

        private async void Button13_Click(object sender, EventArgs e)
        {
            GatewayInfo info = await QLightAPI.GetInfoGatewayUSB(comboBox4.Text);

            if (info.IpAddress == "")
            {
                PrintMessage("[GW USB] Get Info - null");
            }
            else
            {
                string msg = String.Format("[GW USB] Get Info - " +
                    "name:{0}, groupId:{1}, channel:{2}, panId:{3}, txPower:{4}, " + "\n" + 
                    "\t\tipAddr:{5}, subnet:{6}, gw:{7}, mac:{8}, tcpPort:{9}" + "\n" +
                    "\t\tisMaster:{10}, masterIp:{11}, masterPort:{12}, companyId:{13}",
                    info.Name, info.GroupId, info.Channel, info.PandId, info.TxPower,
                    info.IpAddress, info.SubnetMask, info.DefaultGatewayAddress, info.MacAddress, info.TCPPortNumber, 
                    info.IsMaster, info.MasterIp, info.MasterPortNumber, info.CompanyId);
                PrintMessage(msg);
            }
        }

        private void Button10_Click(object sender, EventArgs e)
        {
            if (comboBox4.SelectedIndex == -1) return;
            if (QLightAPI.ConnectGatewayUSB(comboBox4.Text))
            {
                PrintMessage("[GW USB] Connected to " + comboBox4.Text);
                button10.Enabled = false;
                button13.Enabled = true;
                button7.Enabled = true;
            }
            else
            {
                PrintMessage("[GW USB] Fail to connect to " + comboBox1.Text);
            }
            if (QLightAPI.GetConnectedControllerList() != null)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
        }

        private void Button11_Click(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex < 0) return;
            ushort nodeId = ushort.Parse(comboBox3.Text.Split('-')[0]);
            RouterStatus status = QLightAPI.GetStatusRouter(nodeId);
            RefreshRouterStatus(status);

            RouterInfo info = QLightAPI.GetInfoRouter(nodeId);
            RefreshRouterInfo(info);
        }

        private void Button21_Click(object sender, EventArgs e)
        {
            var list = QLightAPI.GetAllRouterList();
            RefreshRouterList(list);
            PrintMessage("Refresh Router list.");
        }

        private void Button8_Click(object sender, EventArgs e)
        {
            if( ushort.TryParse(textBox1.Text, out ushort nodeId) &&
                ushort.TryParse(textBox2.Text, out ushort groupId) )
            {
                if(QLightAPI.AddRouterListManually(nodeId, groupId))
                {
                    PrintMessage(String.Format("Add Router Manually (nodeId:{0}, groupId:{1})", nodeId, groupId));
                    var list = QLightAPI.GetAllRouterList();
                    RefreshRouterList(list);
                }
            }
        }

        LEDState[] controlLedState = new LEDState[5];
        private void LEDButton_Click(object sender, EventArgs e)
        {
            Button bt = (Button)sender;
            LEDState state;
            switch(bt.Name)
            {
                case "BtAllOn":
                    //BtAllOn.BackColor = Color.DarkGray;
                    BtAllOn.BackColor = Color.Gray;
                    BtAllBlink.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    BtAllOff.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    state = LEDState.ON;
                    SetLEDButton("Red", state);     controlLedState[0] = state;
                    SetLEDButton("Orange", state);  controlLedState[1] = state;
                    SetLEDButton("Green", state);   controlLedState[2] = state;
                    SetLEDButton("Blue", state);    controlLedState[3] = state;
                    SetLEDButton("White", state);   controlLedState[4] = state;

                    break;
                case "BtAllBlink":
                    //BtAllOn.BackColor = Color.DarkGray;
                    BtAllOn.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    BtAllBlink.BackColor = Color.Gray;
                    BtAllOff.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    state = LEDState.BLINK;
                    SetLEDButton("Red", state);     controlLedState[0] = state;
                    SetLEDButton("Orange", state);  controlLedState[1] = state;
                    SetLEDButton("Green", state);   controlLedState[2] = state;
                    SetLEDButton("Blue", state);    controlLedState[3] = state;
                    SetLEDButton("White", state);   controlLedState[4] = state;
                    break;
                case "BtAllOff":
                    //BtAllOn.BackColor = Color.DarkGray;
                    BtAllOn.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    BtAllBlink.BackColor = Color.FromArgb(0x55, 0x55, 0x55);
                    BtAllOff.BackColor = Color.Gray;
                    state = LEDState.OFF;
                    SetLEDButton("Red", state);     controlLedState[0] = state;
                    SetLEDButton("Orange", state);  controlLedState[1] = state;
                    SetLEDButton("Green", state);   controlLedState[2] = state;
                    SetLEDButton("Blue", state);    controlLedState[3] = state;
                    SetLEDButton("White", state);   controlLedState[4] = state;
                    break;
                case "BtRedOn":         SetLEDButton("Red", LEDState.ON);       controlLedState[0] = LEDState.ON;  break;
                case "BtRedBlink":      SetLEDButton("Red", LEDState.BLINK);    controlLedState[0] = LEDState.BLINK; break;
                case "BtRedOff":        SetLEDButton("Red", LEDState.OFF);      controlLedState[0] = LEDState.OFF; break;
                case "BtOrangeOn":      SetLEDButton("Orange", LEDState.ON);    controlLedState[1] = LEDState.ON; break;
                case "BtOrangeBlink":   SetLEDButton("Orange", LEDState.BLINK); controlLedState[1] = LEDState.BLINK; break;
                case "BtOrangeOff":     SetLEDButton("Orange", LEDState.OFF);   controlLedState[1] = LEDState.OFF; break;
                case "BtGreenOn":       SetLEDButton("Green", LEDState.ON);     controlLedState[2] = LEDState.ON; break;
                case "BtGreenBlink":    SetLEDButton("Green", LEDState.BLINK);  controlLedState[2] = LEDState.BLINK; break;
                case "BtGreenOff":      SetLEDButton("Green", LEDState.OFF);    controlLedState[2] = LEDState.OFF; break;
                case "BtBlueOn":        SetLEDButton("Blue", LEDState.ON);      controlLedState[3] = LEDState.ON; break;
                case "BtBlueBlink":     SetLEDButton("Blue", LEDState.BLINK);   controlLedState[3] = LEDState.BLINK; break;
                case "BtBlueOff":       SetLEDButton("Blue", LEDState.OFF);     controlLedState[3] = LEDState.OFF; break;
                case "BtWhiteOn":       SetLEDButton("White", LEDState.ON);     controlLedState[4] = LEDState.ON; break;
                case "BtWhiteBlink":    SetLEDButton("White", LEDState.BLINK);  controlLedState[4] = LEDState.BLINK; break;
                case "BtWhiteOff":      SetLEDButton("White", LEDState.OFF);    controlLedState[4] = LEDState.OFF; break;
                default: break;
            }
        }

        private void SetLEDButton(string v, LEDState state)
        {
            switch(v)
            {
                case "Red":
                    BtRedOn.BackColor = (state == LEDState.ON)?Color.Red: Color.FromArgb(0x55, 0x55, 0x55);
                    BtRedBlink.BackColor = (state == LEDState.BLINK) ? Color.Red : Color.FromArgb(0x55, 0x55, 0x55);
                    BtRedOff.BackColor = (state == LEDState.OFF) ? Color.Red : Color.FromArgb(0x55, 0x55, 0x55);
                    break;
                case "Orange":
                    BtOrangeOn.BackColor = (state == LEDState.ON) ? Color.DarkOrange : Color.FromArgb(0x55, 0x55, 0x55);
                    BtOrangeBlink.BackColor = (state == LEDState.BLINK) ? Color.DarkOrange : Color.FromArgb(0x55, 0x55, 0x55);
                    BtOrangeOff.BackColor = (state == LEDState.OFF) ? Color.DarkOrange : Color.FromArgb(0x55, 0x55, 0x55);
                    break;
                case "Green":
                    BtGreenOn.BackColor = (state == LEDState.ON) ? Color.SeaGreen : Color.FromArgb(0x55, 0x55, 0x55);
                    BtGreenBlink.BackColor = (state == LEDState.BLINK) ? Color.SeaGreen : Color.FromArgb(0x55, 0x55, 0x55);
                    BtGreenOff.BackColor = (state == LEDState.OFF) ? Color.SeaGreen : Color.FromArgb(0x55, 0x55, 0x55);
                    break;
                case "Blue":
                    BtBlueOn.BackColor = (state == LEDState.ON) ? Color.DodgerBlue : Color.FromArgb(0x55, 0x55, 0x55);
                    BtBlueBlink.BackColor = (state == LEDState.BLINK) ? Color.DodgerBlue : Color.FromArgb(0x55, 0x55, 0x55);
                    BtBlueOff.BackColor = (state == LEDState.OFF) ? Color.DodgerBlue : Color.FromArgb(0x55, 0x55, 0x55);
                    break;
                case "White":
                    BtWhiteOn.BackColor = (state == LEDState.ON) ? Color.White : Color.FromArgb(0x55, 0x55, 0x55);
                    BtWhiteBlink.BackColor = (state == LEDState.BLINK) ? Color.White : Color.FromArgb(0x55, 0x55, 0x55);
                    BtWhiteOff.BackColor = (state == LEDState.OFF) ? Color.White : Color.FromArgb(0x55, 0x55, 0x55);
                    break;
                default: break;
            }
        }

        private void SetSoundButton(ushort soundNumber)
        {
            BtSound1.BackColor = Color.DimGray; BtSound1.Text = "OFF";
            BtSound2.BackColor = Color.DimGray; BtSound2.Text = "OFF";
            BtSound3.BackColor = Color.DimGray; BtSound3.Text = "OFF";
            BtSound4.BackColor = Color.DimGray; BtSound4.Text = "OFF";
            BtSound5.BackColor = Color.DimGray; BtSound5.Text = "OFF";

            switch (soundNumber)
            {
                case 1: BtSound1.BackColor = Color.DarkOrange; BtSound1.Text = "ON"; break;
                case 2: BtSound2.BackColor = Color.DarkOrange; BtSound2.Text = "ON"; break;
                case 3: BtSound3.BackColor = Color.DarkOrange; BtSound3.Text = "ON"; break;
                case 4: BtSound4.BackColor = Color.DarkOrange; BtSound4.Text = "ON"; break;
                case 5: BtSound5.BackColor = Color.DarkOrange; BtSound5.Text = "ON"; break;
                default: break;
            }
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex == -1) return;
            ushort[] nodeId = new ushort[] { ushort.Parse(comboBox3.Text.Split('-')[0]) };
            bool result = QLightAPI.ControlRoutersLED(nodeId, controlLedState[0], controlLedState[1], controlLedState[2], controlLedState[3], controlLedState[4]);
            if(result)
            {
                PrintMessage(String.Format("Sent the control LED msg to {0}.", comboBox3.Text));
            }
            else
            {
                PrintMessage(String.Format("Fail to Send the control LED msg to {0}.", comboBox3.Text));
            }
        }

        private void SoundButton_Click(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex < 0) return;

            Button bt = sender as Button;
            if(bt.Text == "ON")
            {
                bt.BackColor = Color.DimGray;
                bt.Text = "OFF";
            }
            else
            {
                bt.BackColor = Color.DarkOrange;
                bt.Text = "ON";
            }
 
            ushort[] nodeIds = new ushort[] { ushort.Parse(comboBox3.Text.Split('-')[0]) };
            int num = 0;
            switch(bt.Name)
            {
                case "BtSound1": num = bt.Text == "ON" ? 1 : 0; break;
                case "BtSound2": num = bt.Text == "ON" ? 2 : 0; break;
                case "BtSound3": num = bt.Text == "ON" ? 3 : 0; break;
                case "BtSound4": num = bt.Text == "ON" ? 4 : 0; break;
                case "BtSound5": num = bt.Text == "ON" ? 5 : 0; break;
                default: break;
            }
            bool result = QLightAPI.ControlRoutersSound(nodeIds, (ushort)num);
            if (result)
            {
                PrintMessage(String.Format("Sent the control SOUND msg to {0}.", comboBox3.Text));
            }
            else
            {
                PrintMessage(String.Format("Fail to Send the control SOUND msg to {0}.", comboBox3.Text));
            }
            SetSoundButton((ushort)num);
        }

        private void Button18_Click(object sender, EventArgs e)
        {
            if(uint.TryParse(textBox3.Text, out uint sec))
            {
                if(QLightAPI.SetScanInterval(sec))
                {
                    PrintMessage("Scan Interval is changed : " + sec + " second(s)");
                }
            }
        }

        private void Button9_Click(object sender, EventArgs e)
        {
            if(ushort.TryParse(textBox1.Text, out ushort nodeId))
            {
                if(QLightAPI.DeleteRouterList(nodeId))
                {
                    PrintMessage(String.Format("Deleted {0} in the Router list.", nodeId));
                    var list = QLightAPI.GetAllRouterList();
                    RefreshRouterList(list);
                }
            }
        }

        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (cb.SelectedIndex == -1) return;
            comboBox2.SelectedIndex = cb.SelectedIndex;
            comboBox3.SelectedIndex = cb.SelectedIndex;
            if (!ushort.TryParse(cb.Text.Split('-')[0], out ushort nodeId)) return;
            ushort groupId = QLightAPI.GetGroupIdFromRouterList(nodeId);
            textBox1.Text = nodeId.ToString();
            textBox2.Text = groupId.ToString();

            RouterStatus status = QLightAPI.GetStatusRouter(nodeId);
            RefreshRouterStatus(status);

            RouterInfo info = QLightAPI.GetInfoRouter(nodeId);
            RefreshRouterInfo(info);
        }

        private async void Button17_Click(object sender, EventArgs e)
        {
            var gwList = await QLightAPI.FindMacGateways();
            if (gwList == null || gwList.Count == 0)
            {
                PrintMessage("[GW LAN] There is no gateway...");
                return;
            }

            string[] ipList = gwList.Values.ToArray();
            Array.Sort(ipList);
            comboBox5.Items.Clear();
            comboBox5.Items.AddRange(ipList);
            PrintMessage(String.Format("[GW LAN] Found {0} gateway(s)...", ipList.Length));
        }

        private void Button16_Click(object sender, EventArgs e)
        {
            if (comboBox5.SelectedIndex == -1) return;
            PrintMessage("[GW LAN] Try to connect to " + comboBox5.Text);
            if (QLightAPI.ConnectGatewayLAN(comboBox5.Text, 32177))
            {
                PrintMessage("[GW LAN] Connected to " + comboBox5.Text);
                button16.Enabled = false;
                button15.Enabled = true;
                button14.Enabled = true;
            }
            else
            {
                PrintMessage("[GW LAN] Fail to connect to " + comboBox5.Text);
            }
            if(QLightAPI.GetConnectedControllerList().Count > 0)
            {
                panel1.Enabled = true;
                panel2.Enabled = true;
            }
            else
            {
                panel1.Enabled = false;
                panel2.Enabled = false;
            }
        }

        private async void Button14_Click(object sender, EventArgs e)
        {
            GatewayInfo info = await QLightAPI.GetInfoGatewayLAN(comboBox5.Text);

            if (info.IpAddress == "")
            {
                PrintMessage("[GW LAN] Get Info - null");
            }
            else
            {
                string msg = String.Format("[GW LAN] Get Info - " +
                    "name:{0}, groupId:{1}, channel:{2}, panId:{3}, txPower:{4}, " + "\n" +
                    "\t\tipAddr:{5}, subnet:{6}, gw:{7}, mac:{8}, tcpPort:{9}" + "\n" +
                    "\t\tisMaster:{10}, masterIp:{11}, masterPort:{12}, companyId:{13}",
                    info.Name, info.GroupId, info.Channel, info.PandId, info.TxPower,
                    info.IpAddress, info.SubnetMask, info.DefaultGatewayAddress, info.MacAddress, info.TCPPortNumber,
                    info.IsMaster, info.MasterIp, info.MasterPortNumber, info.CompanyId);
                PrintMessage(msg);
            }
        }

        private void Button24_Click(object sender, EventArgs e)
        {
            if (ushort.TryParse(textBox4.Text, out ushort ttl))
            {
                if (QLightAPI.SetTTL(ttl))
                {
                    PrintMessage("Send TTL is changed : " + ttl + ".");
                }
            }
        }

        private void Button19_Click(object sender, EventArgs e)
        {
            if (ushort.TryParse(textBox5.Text, out ushort num) && num >=1 && num <= 10)
            {
                if (QLightAPI.SetSendNumber(num))
                {
                    PrintMessage("Send Number is changed : " + num + ".");
                }
            }
        }

        private void Button26_Click(object sender, EventArgs e)
        {
            PrintMessage("Sent the Request to search Routers.");
            QLightAPI.SearchRouters();
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null)
            {
                if (QLightAPI.GetConnectStatusUSBDongle(comboBox1.Text))
                {
                    button2.Enabled = false;
                    button3.Enabled = true;
                    button4.Enabled = true;
                }
                else
                {
                    button2.Enabled = true;
                    button3.Enabled = false;
                    button4.Enabled = false;
                }
            }
        }

        private void ComboBox4_SelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBox4.SelectedItem != null)
            {
                if (QLightAPI.GetConnectStatusGatewayUSB(comboBox4.Text))
                {
                    button10.Enabled = false;
                    button7.Enabled = true;
                    button13.Enabled = true;
                }
                else
                {
                    button10.Enabled = true;
                    button7.Enabled = false;
                    button13.Enabled = false;
                }
            }
        }

        private void ComboBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox5.SelectedItem != null)
            {
                if (QLightAPI.GetConnectStatusGatewayLAN(comboBox5.Text))
                {
                    button16.Enabled = false;
                    button15.Enabled = true;
                    button14.Enabled = true;
                }
                else
                {
                    button16.Enabled = true;
                    button15.Enabled = false;
                    button14.Enabled = false;
                }
            }
        }

        private void ComboBox5_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1) return;
            ComboBox comboBox = sender as ComboBox;
            Font font = comboBox.Font;
            Brush brush = Brushes.Black;
            string text = comboBox.Items[e.Index].ToString();

            if (QLightAPI.GetConnectStatusGatewayLAN(text))
            {
                font = new Font(font, FontStyle.Bold);
                brush = Brushes.Green;
            }

            e.Graphics.DrawString(text, font, brush, e.Bounds);
        }

        private void ComboBox4_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1) return;
            ComboBox comboBox = sender as ComboBox;
            Font font = comboBox.Font;
            Brush brush = Brushes.Black;
            string text = comboBox.Items[e.Index].ToString();

            if (QLightAPI.GetConnectStatusGatewayUSB(text))
            {
                font = new Font(font, FontStyle.Bold);
                //brush = Brushes.Green;
            }

            e.Graphics.DrawString(text, font, brush, e.Bounds);
        }

        private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1) return;
            ComboBox comboBox = sender as ComboBox;
            Font font = comboBox.Font;
            Brush brush = Brushes.Black;
            string text = comboBox.Items[e.Index].ToString();

            if (QLightAPI.GetConnectStatusUSBDongle(text))
            {
                font = new Font(font, FontStyle.Bold);
                //brush = Brushes.Green;
            }

            e.Graphics.DrawString(text, font, brush, e.Bounds);
        }

        private void Button29_Click(object sender, EventArgs e)
        {
            List<ControllerInfo> list = QLightAPI.GetConnectedControllerList();
            if (list == null) PrintMessage("(No list)");
            else
            {
                string printMsg = "\n- Connected Controller List - \n";
                foreach (ControllerInfo info in list)
                {
                    printMsg += String.Format("{0}. Addr:{1}, Name:{2}, GroupId:{3}\n", list.IndexOf(info), info.Address, info.Name, info.GroupId);
                }
                PrintMessage(printMsg);
            }
        }

        private void Button25_Click(object sender, EventArgs e)
        {
            if(comboBox6.Text.Equals("ALL"))
            {
                if (QLightAPI.SetScanMethod(ScanMethod.ALL))
                {
                    PrintMessage("Scan Method is changed to " + comboBox6.Text + ".");
                }
            }
            else if(comboBox6.Text.Equals("GROUP"))
            {
                if (QLightAPI.SetScanMethod(ScanMethod.GROUP))
                {
                    PrintMessage("Scan Method is changed to " + comboBox6.Text + ".");
                }
            }
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            ClearRouterList();
            PrintMessage("Clear Router list.");
        }
    }
}
