using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GateBrakeSdk;
using System.Runtime.InteropServices;

namespace GateBrakeDemo
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();

        public Form1()
        {
            InitializeComponent();
            //AllocConsole();
            Config.LoadParam();
            cbAngle.Text = "90";
            cbYuzu.SelectedIndex = 0;
            cbSpeedH.SelectedIndex = 0;
            cbSpeedL.SelectedIndex = 0;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            tbIp.Text = Config.lastip;
            tbDestIp.Text = Config.lastip;
            GateBrake.OnLogerEvent += new GateBrake.LogerEventHandler(GateBrake_OnLogerEvent);
            GateBrake.OnDataArrivedEvent += new GateBrake.OnDataArrivedEventHandler(gb_OnDataArrivedEvent);
            GateBrake.OnDeviceStateChangedEvent += new GateBrake.StateChangedEventHandler(gb_OnDeviceStateChangedEvent);
            GateBrake.OnDeviceMonitorEvent += new GateBrake.DeviceMonitorEventHandler(gb_OnDeviceMonitorEvent);
            GateBrake.OnUpdateInfoEvent += new GateBrake.UpdateInfoEventHandler(GateBrake_OnUpdateInfoEvent);
        }
        private void GateBrake_OnUpdateInfoEvent(String ip, String status, Dictionary<String, String> param)
        {
            try
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    if (status.Equals("Rconf") || status.Equals("Sconf"))
                    {
                        String angle = param["angle"];
                        String autoclose = param["autoclose"];
                        String digangsign = param["digangsign"];
                        String yuzu = param["yuzu"];
                        String count = param["count"];
                        String vangle = param["vangle"];
                        String hangle = param["hangle"];
                        String speed = param["speed"];

                        cbAngle.Text = angle;

                        int Iautoclose = Int32.Parse(autoclose);
                        cbAutoClose.Checked = Iautoclose != 0;
                        if (Iautoclose >= 3 && Iautoclose <= 60)
                        {
                            nAutoClose.Visible = true;
                            nAutoClose.Value = Iautoclose;
                        }
                        int Idigangsign = Int32.Parse(digangsign);
                        cbDigangsign.Checked = Idigangsign != 0;
                        if (Idigangsign >= 3 && Idigangsign <= 60)
                        {
                            nDigangsign.Visible = true;
                            nDigangsign.Value = Idigangsign;
                        }
                        cbYuzu.SelectedIndex = Int32.Parse(yuzu);
                        checkBox1.Checked = "1".Equals(count);
                        nVangle.Value = Int32.Parse(vangle);
                        nHangle.Value = Int32.Parse(hangle);

                        int nspeed = Int32.Parse(speed);
                        try
                        {
                            cbSpeedH.SelectedIndex = (nspeed & 0x000000f0) >> 4;
                            cbSpeedL.SelectedIndex = (nspeed & 0x0000000f);
                        }
                        catch (Exception) { }
                    }
                    else if (status.Equals("RMAC") || status.Equals("SMAC"))
                    {
                        String mac = param["mac"];
                        tbMac.Text = "" + mac;
                    }
                    
                    richTextBox1.AppendText("GateBrake_OnUpdateInfoEvent -----> ip:" + ip + " status:" + status  + "\r\n");
                });
            }
            catch (Exception) { }
        }
        private void GateBrake_OnLogerEvent(String msg)
        {
            try
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    richTextBox1.AppendText(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + ":" + msg + "\r\n");
                });
            }
            catch (Exception) { }
        }

        private void gb_OnDataArrivedEvent(GateBrakeSdk.GateBrake.ROADGATE_INFO_STRUCT info)
        {
        }
        private void gb_OnDeviceStateChangedEvent(String ip, bool state)
        {
            Console.WriteLine("ip {0} statechange:{1}", ip, state);
        }
        private void gb_OnDeviceMonitorEvent(String ip, int state, bool isPressed)
        {
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            bool ret = GateBrake.Connect(tbIp.Text.Trim());
            MessageBox.Show("Connect return " + ret, "Info", MessageBoxButtons.OK, ret ? MessageBoxIcon.Information : MessageBoxIcon.Error);
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            bool ret = GateBrake.DisConnect(tbIp.Text.Trim());
            MessageBox.Show("DisConnect return " + ret, "Info", MessageBoxButtons.OK, ret ? MessageBoxIcon.Information : MessageBoxIcon.Error);
        }

        private void btnInitialize_Click(object sender, EventArgs e)
        {
            int port = Int32.Parse(tbPort.Text.Trim());
            bool ret = GateBrake.Initialize(tbIp.Text.Trim(), port, null, null);
            if (ret)
            {
                Config.lastip = tbIp.Text.Trim();
                Config.SaveToFile();
            }
            MessageBox.Show("Initialize return " + ret, "Info", MessageBoxButtons.OK, ret?MessageBoxIcon.Information:MessageBoxIcon.Error);
        }

        private void btnUnInitialize_Click(object sender, EventArgs e)
        {
            bool ret = GateBrake.UnInitialize(tbIp.Text.Trim());
            MessageBox.Show("UnInitialize return " + ret, "Info", MessageBoxButtons.OK, ret ? MessageBoxIcon.Information : MessageBoxIcon.Error);
        }

        private void btnSetDeviceInfo_Click(object sender, EventArgs e)
        {
            GateBrake.ROADGATE_NETCONFIG_STRUCT info = new GateBrake.ROADGATE_NETCONFIG_STRUCT();
            info.deviceName = "device1";
            info.srcIp = tbIp.Text.Trim();
            info.destIp = tbDestIp.Text.Trim();
            info.mac = tbMac.Text.Trim();
            if (tbGate.Text.Trim().Length > 0)
            {
                info.gate = tbGate.Text.Trim();
            }
            if (tbMask.Text.Trim().Length > 0)
            {
                info.mask = tbMask.Text.Trim();
            }
            bool ret = GateBrake.SetDeviceInfo(info);
        }

        private void btnGetDeviceInfo_Click(object sender, EventArgs e)
        {
            String[] deviceInfo = GateBrake.GetDeviceInfo(tbIp.Text.Trim());
            if (deviceInfo != null)
            {
                String model = deviceInfo[0];
                String hdver = deviceInfo[1];
                String mac = deviceInfo[2];
                String date = deviceInfo[3];
                String sn = deviceInfo[4];
                if (mac != null)
                {
                    tbMac.Text = mac;
                }
                MessageBox.Show("设备型号为：" + model + " 硬件版本为:" + hdver + " MAC地址为" + mac + " 生产日期为" + date + " 序列号为" + sn);
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            GateBrake.RemoveAllDevices();
        }

        private void btnQuerryController_Click(object sender, EventArgs e)
        {
            GateBrake.QuerryController(tbIp.Text.Trim());
        }

        private void btnConfigController_Click(object sender, EventArgs e)
        {
            if (cbSpeedL.SelectedIndex == 2)
            {
                MessageBox.Show("起落速度参数不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int angle = Int32.Parse(cbAngle.Text);
            int autoclose = 0;
            if (cbAutoClose.Checked)
            {
                autoclose = (int)nAutoClose.Value;
            }
            else
            {
                autoclose = 0;
            }

            int digangsign = 0;
            if (cbDigangsign.Checked)
            {
                digangsign = (int)nDigangsign.Value;
            }
            else
            {
                digangsign = 0;
            }
            int yuzu = (int)cbYuzu.SelectedIndex;
            bool count = checkBox1.Checked;
            int vangle = (int)nVangle.Value;
            int hangle = (int)nHangle.Value;
            int speed = cbSpeedH.SelectedIndex * 16 + cbSpeedL.SelectedIndex;


            if (cbSpeedL.Text.Trim().Length == 0)
            {
                MessageBox.Show("起落速度不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        
            GateBrake.ConfigController(tbIp.Text.Trim(), angle, autoclose, digangsign, yuzu, count, vangle, hangle, speed);
        }

        private void btnSendCommand_Click(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 0);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 1);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 2);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 3);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 4);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            GateBrake.SendCommand(tbIp.Text.Trim(), 5);
        }

        private void cbAutoClose_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAutoClose.Checked)
            {
                nAutoClose.Visible = true;
            }
            else
            {
                nAutoClose.Visible = false;
            }
        }

        private void cbDigangsign_CheckedChanged(object sender, EventArgs e)
        {
            if (cbDigangsign.Checked)
            {
                nDigangsign.Visible = true;
            }
            else
            {
                nDigangsign.Visible = false;
            }
        }
    }
}
