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.Deployment;
using System.Deployment.Application;
using System.Reflection;
using System.Diagnostics;
using UsbLibrary;


namespace USB_SMB
{
    public partial class Form1 : Form
    {
        //globální proměnné
        uint cis1, cis2, cis3;
        UInt16 count_of_batt = 1;
        smb batt0 = new smb();
        List<smb> batteries = new List<smb>();
        byte[] pom1 = { 0, 3, 7, 6 };       //typ "pole bajtů"
        byte r_index=0;
        byte[] Auto_commands = new byte[12] { 8, 9, 15, 16, 23, 24, 25, 27, 28, 182, 183, 184 };

//------------------
        public Form1() //Inicializace - nastavení VID,PID
        {
            InitializeComponent();
            this.usb.ProductId = 0x05df;
            this.usb.VendorId = 0x16c0;
        }
//----------------- událsot Form create -------------
        private void Form1_Load(object sender, EventArgs e) //při načtení form1
        {
           
            pictureBox1.Visible = false;
            timer1.Enabled = false;
            this.Text = "Smart Battery Monitor";
        //- version -----
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                System.Deployment.Application.ApplicationDeployment ad = System.Deployment.Application.ApplicationDeployment.CurrentDeployment;
                this.Text = "Smart Battery Monitor ver."+ad.CurrentVersion.ToString();
            }           
            
            
            
        }   
//-------------------------------
        private void usb_OnDeviceRemoved(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new EventHandler(usb_OnDeviceRemoved), new object[] { sender, e });
            }
            else
            {
                toolStripStatusLabel1.Text = "Device removed";
                usb_err();
            }

        }
//-----------------------------
        private void usb_OnDeviceArrived(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "Found HID Device";
            set_checksum();
            usb_ok();
        }
//------------------------------
        private void usb_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "Found HID Device";
            set_checksum();
            usb_ok();
        }
//------------------------------
        private void usb_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new EventHandler(usb_OnSpecifiedDeviceRemoved), new object[] { sender, e });
            }
            else
            {
                toolStripStatusLabel1.Text = "Device removed";
                usb_err();
            }

        }
//---------------------------------
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            usb.RegisterHandle(Handle);
        }
//---------------------------------
        protected override void WndProc(ref Message m)
        {
            usb.ParseMessages(ref m);
            base.WndProc(ref m);	// pass message on to base form
        }
//------------ PŘÍCHOD DAT  ------------------------
//-*************************************************
        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new DataRecievedEventHandler(usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                usb_ok();
                if (pictureBox1.Visible == false)
                {
                    pictureBox1.Visible = true;
                }
                else
                {
                    pictureBox1.Visible = false;
                }
                //-------- interrupt - incomming data **********************
                //-******************************************************
                cis1 = (uint)args.data[1];
                cis2 = (uint)args.data[2];
                cis3 = (uint)args.data[3];
                uint block16b = 0;

                label2.Text = cis1.ToString();
                label3.Text = cis2.ToString();
                label4.Text = cis3.ToString();
                //----- detection address----------
                
                if (cis1 == 48)
                {
                    if (cis2 != 0)
                    {
                        if (cis3==0)
                        {
                            textBox4.Text = cis2.ToString();
                            smb_ok();
                        }
                        else
                        {
                            textBox4.Text = cis2.ToString() + ", " + cis3.ToString();
                            smb_err();
                        }
                    }
                    else
                    {
                        textBox4.Text = "error address";
                        smb_err();
                    }
                }
                //------- čtení ze Smart Battery-identifikace commandu, uložení do tabulky
                //------------------------------------------------------------
                block16b = (cis2 * 256) + cis3;
                switch(cis1){
                    case 8:
                        {
                            batt0.Temperature = block16b;
                            break;
                        }
                    case 9:
                        {
                            batt0.Voltage = block16b;
                            break;
                        }
                    case 15:
                        {
                            batt0.Remaining_Capacity = block16b;
                            break;
                        }
                    case 16:
                        {
                            batt0.Full_Capacity = block16b;
                            break;
                        }
                    case 23:
                        {
                            batt0.Cycle_Count = Convert.ToUInt16(block16b);
                            break;
                        }
                    case 24:
                        {
                            batt0.Designed_Capacity = block16b;
                            break;
                        }
                    case 25:
                        {
                            batt0.Designed_Voltage = block16b;
                            break;
                        }
                    case 27:
                        {
                            batt0.Manufacture_date = Convert.ToUInt16(block16b);
                            break;
                        }
                    case 28:
                        {
                            batt0.S_Number = Convert.ToUInt16(block16b);
                            break;
                        }
                    case 32:
                        {
                            batt0.Manufacturer = batt0.Manufacturer + Convert.ToChar(cis2) + Convert.ToChar(cis3);
                            break;
                        }
                    case 33:
                        {
                            batt0.Name = batt0.Name + Convert.ToChar(cis2) + Convert.ToChar(cis3);
                            break;
                        }
                    case 34:
                        {
                            batt0.Chemistry = batt0.Chemistry + Convert.ToChar(cis2) + Convert.ToChar(cis3);
                            break;
                        }
                    case 47:            //checksum En/Disable
                        {
                            if (cis2 == 0)
                            {
                                checkBox2.Checked = false;
                            }
                            else
                                checkBox2.Checked = true;

                            break;
                        }
                    
                }//switch
                batt_overview();                    //view all data form batt
                if ((cis1 >= 32) && (cis1 <= 35))
                    textBox6.Text = textBox6.Text + "-" + cis2.ToString() + "-" + cis3.ToString();
                if((cis1>=0)&&(cis1<=35))
                    smb_ok();
            }

        }
//----- aktivita timeru - automat odesílání ------------------
        //************************************************************
        private void timer1_Tick(object sender, EventArgs e)
        {
            //-HELP-//
            //lze použít i BitConverter.GetBytes(c_out);
            //label5.Text = BitConverter.ToString(pom1, 0, 3);


            if (r_index == 12)      //stoop automatic reading
            {
                timerstop();
                if ((batt0.Month != 0) || (batt0.Remaining_Capacity != 0)||(batt0.Cycle_Count!=0)||(batt0.Name!=null)||(batt0.Voltage!=0)||(batt0.S_Number!=0))
                {
                    count_of_batt++;
                    batteries.Add(batt0);
                }
                list_refresh();

            }
            else
            {
                send_command(Auto_commands[r_index]);
                r_index++;
            }
        }

//button - user querry -----------------------------------
        //***************************************************
        private void button1_Click(object sender, EventArgs e)
        {
            smb_err();
            try
            {
                pom1[1] = Convert.ToByte(textBox1.Text);
                if (radioButton1.Checked)
                {
                    pom1[1] += 50;
                }
                else
                {
                    pom1[1] += 100;
                }
                pom1[2] = Convert.ToByte(textBox2.Text);
                pom1[3] = Convert.ToByte(textBox3.Text);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                MessageBox.Show("Nember error");
            }
            try
            {
                usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
                usb_ok();
            }
            catch (Exception ex)
            {
                usb_err();
                Console.WriteLine(ex.ToString());
            }
            if (radioButton2.Checked)
            {
                radioButton2.Checked = false;
                radioButton1.Checked = true;
            }
            
        }
//------------------
        private void button3_Click(object sender, EventArgs e)
        {
            textBox4.Text = "";
            pom1[1] = 48;
            pom1[2]=0;
            pom1[3] = 0;
            smb_err();
            try
            {
                usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
            }
            catch
            {
                usb_err();
            }
            
        }
//------------------
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                pom1[1] = 49;
                pom1[2] = Convert.ToByte(textBox4.Text);
                pom1[3] = 0;
                textBox4.Text = "";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                textBox4.Text = "number only";
            }
            try
            {
                usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
            }
            catch 
            {
                usb_err();
            }
        }
//------------------
        private void button4_Click(object sender, EventArgs e)
        {
            checkBox2.Enabled = false;
            checkBox1.Checked = false;
            smb nova = new smb();
            batt0 = nova;           //vynulování batt0 (globální)
            batt0.No = count_of_batt;
            timer1.Enabled = true;
            r_index = 0;            
        }
//------------------        
        private void timerstop()
        {
            //r_index = 0;
            timer1.Enabled = false;
            checkBox2.Enabled = true;
        }
//------------------
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
//------------------
        private void usb_err()
        {
            button5.Text = "X";
            button5.BackColor = System.Drawing.Color.Red;
            button5.Visible = true;
        }
//------------------
        private void usb_ok()
        {
            button5.BackColor = System.Drawing.Color.Lime;
            button5.Text = ">";
            button5.Visible = true;
        }
//------------------        
        private void smb_ok()
        {
            button8.BackColor=System.Drawing.Color.Lime;
            button8.Text=">";
            button8.Visible=true;
        }
//-----------------
       private void smb_err()
        {
            button8.BackColor = System.Drawing.Color.Red;
            button8.Text="X";
            button8.Visible=true;
        }
//------------------
        private void button4_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Read all data from Smart Batt";
        }
//------------------
        private void button4_MouseLeave(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "---";
        }
//------------------
        private void button6_Click(object sender, EventArgs e)
        {
            int converted = 0;
            smb_err();
            pom1[1] = 150;
            bool resultBool = int.TryParse(textBox5.Text, out converted);
            if (resultBool == true)
            {
                if ((converted >= 32) && (converted <= 35))
                    pom1[1] += Convert.ToByte(converted);
                else
                    textBox5.Text = "Error command";
                pom1[2] = pom1[3] = 0;

                try
                {
                    usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
                    usb_ok();
                }
                catch (Exception ex)
                {
                    usb_err();
                    Console.WriteLine(ex.ToString());
                }
            }
            else
                textBox5.Text = "Error command";

            
        }
//------------------
        private void send_command(byte index)
        {
            if (index != 0)
            {
                pom1[1] = index;
                pom1[2] = 0;
                pom1[3] = 0;
                
                try
                {
                    usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
                    usb_ok();
                }
                catch
                {
                    usb_err();
                    timerstop();
                }
            }
        }
//------------------
        private void timer_refresh()
        {
            timer1.Stop();
            timer1.Start();
        }
//------------------
        private void button7_Click(object sender, EventArgs e)
        {
            textBox6.Text = "";
        }
//------------------
        private void list_refresh()
        {
            int i;
            listBox1.Items.Clear();
            for (i = 0; i < batteries.Count;i++)
            {
                    listBox1.Items.Add(batteries[i].No.ToString() + ". " + batteries[i].S_Number.ToString() + ", " + batteries[i].Manufacturer + ", " + batteries[i].Name);
            }

        }
//------------------
        private void button9_Click(object sender, EventArgs e)
        {
            try
            {
                batteries.RemoveAt(listBox1.SelectedIndex);
                list_refresh();
            }
            catch { }
        }
//------------------
        private void button10_Click(object sender, EventArgs e)
        {
            batteries.Clear();
            list_refresh();
        }
//------------------
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            
            if (checkBox1.Checked)
            {
                timer2.Enabled = true;
                timer1.Enabled = false;
            }
            else
                timer2.Enabled = false;
        }
//------------------ autodetect --------------
        private void timer2_Tick(object sender, EventArgs e)
        {
            pom1[1] = 48;
            try
            {
                usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
            }
            catch
            {
                usb_err();
            }
        }
//------------------
        private void batt_overview()
        {
            label9.Text = batt0.Temperature.ToString();
            label10.Text = batt0.Voltage.ToString();
            label12.Text = batt0.Cycle_Count.ToString();
            label13.Text = batt0.Day.ToString();
            label14.Text = batt0.Month.ToString();
            label15.Text = batt0.Year.ToString();
            lblChemistry.Text = batt0.Chemistry;
            lblName.Text = batt0.Name;
            lblSerial.Text = batt0.S_Number.ToString();
            lblManufacturer.Text = batt0.Manufacturer;
            lblRemCapacity.Text = batt0.Remaining_Capacity.ToString();
            lblFullCapacity.Text = batt0.Full_Capacity.ToString();
            lblDesCapacity.Text = batt0.Designed_Capacity.ToString();
            lblDesVoltage.Text = batt0.Designed_Voltage.ToString();

        }
//------------------
        private void button11_Click(object sender, EventArgs e)
        {
            if (batteries.Count <1)
                MessageBox.Show("Empty list");
            saveFileDialog1.ShowDialog();
                
        }
//------------------
        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {                        
            batt0.Save_to_txt(batteries, saveFileDialog1.FileName);
        }
//----------------
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 formular = new Form2();
            formular.ShowDialog();           
        }
//------------------
        private void listBox1_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Select one item";
        }
//------------------
        private void button10_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Clear list of batteries";
        }
//------------------
        private void button9_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Delete selected line (in list)";
        }
//------------------
        private void button11_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Save list to .txt file";
        }
//------------------
        private void checkBox1_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Start/Stop automatic detection of presence Smart Battery";
        }
//------------------
        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Blinking during data transfer";
        }
//------------------
        private void button3_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Detect presence of Smart Battery (Detect Bus Address)";
        }
//------------------
        private void button2_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Use own address (user edit) for comunication with Smart Battery";
        }
//------------------
        private void button1_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Read/Write 16b word to Smart Battery";
        }
//------------------
        private void button6_MouseEnter(object sender, EventArgs e)
        {
            toolStripStatusLabel3.Text = "Send number of command to Read BLOCK (32, 33, 34, 35)";
        }
//------------------
        private void commandHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form3 form_3 = new Form3();
            form_3.Show();
        }
//------------------
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            set_checksum();        
        }
//------------------
        private void set_checksum(){
            pom1[1] = 47;
            if (checkBox2.Checked == true)
                pom1[2] = 1;
            else
                pom1[2] = 0;
            try
            {
                usb.SpecifiedDevice.SendData(pom1); //odeslání dat - pole pom1[]
            }
            catch
            {
                usb_err();
            }
        }
//------------------
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(listBox1.SelectedIndex>=0)
            batt0=batteries[listBox1.SelectedIndex];
            batt_overview();
        }



    }//class
}//namespace
