using System;
using System.IO.Ports;
using System.Linq;
using System.Windows.Forms;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;


namespace HMI
{
    public partial class principal : Form
    {
        SqlCommand cmd;
        SqlConnection cn;
        SqlDataReader dr;
        int cant_obs=0;
        int cant_acep=0;
        int cant_cat1=0;
        int cant_cat2=0;
        int cant_cat3=0;
        int cant_rech=0;
        double vol_obs=0;
        double vol_acep=0;
        double vol_cat1=0;
        double vol_cat2=0;
        double vol_cat3=0;
        double vol_rech=0;

        string rx;
        string puerto;
        string categoria ="";
        int pos;
        int x_graph;
        int cont1 = 0;
        int cont2 = 0;
        int cont3 = 0;
        int diam;
        int laser1;
        int laser2;
        int flag1;
        int flag2;
        int flag_a1;
        int flag_a2;
        int flag_a3;
        int suma_diam;
        int prom_diam;
        float largo;
        float volumen;
        float PI = 3.14159265358979f;
        string fecha = DateTime.Today.ToString("dd/MM/yyyy");
        
       
        public principal()
        {
        
        InitializeComponent();
 
            string[] puertos = SerialPort.GetPortNames();
            foreach (string mostrar in puertos)
            {
                boxpuertos.Items.Add(mostrar);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            cn = new SqlConnection("Data Source=.;Initial Catalog=data_hmi;Integrated Security=True");
            graph1.Legends.Clear();
            graph1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Range;
            act1.Text = "Activar";
            act2.Text = "Activar";
            act3.Text = "Activar";
        }
// ************************* SELECCIÓN PUERTO *******************************
        private void boxpuertos_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort1.Close();
            serialPort1.Dispose();
            puerto = boxpuertos.Text;
            serialPort1.PortName = puerto;
            boton_conex.Text = "Conectar";
            CheckForIllegalCrossThreadCalls = false;


        }


// *********************** CONECXION PUERTO *********************************
        public void boton_conex_Click(object sender, EventArgs e)
        {
            string selec_largo = text_largo.Text;
            if (selec_largo != "")
            {
                float largo = ((Convert.ToSingle(selec_largo)) / 10f);
                if (serialPort1.IsOpen == false)
                {
                    boton_conex.Text = "Desconectar";
                    serialPort1.Open();
                    serialPort1.Write("0");
                    serialPort1.Write("2");
                    serialPort1.Write("4");
                }
                else
                {
                    boton_conex.Text = "Conectar";
                    serialPort1.Close();
                    serialPort1.Dispose();
                    diametro.Text = "";
                }
            }
            else {
                MessageBox.Show("No se ha seleccionado un largo para el rollizo", "Error al conectar", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

// *********************** BOTÓN SALIR **************************************
        private void salir_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
            serialPort1.Dispose();
            Close();
        }


        public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string selec_largo = text_largo.Text;
            float largo = ((Convert.ToSingle(selec_largo)) / 10f);

            cn.Open();
            SqlCommand cm = new SqlCommand("select COUNT(rollizo) from rollizos", cn);
            cant_obs = Convert.ToInt16(cm.ExecuteScalar());
            cn.Close();
                
            if ( cant_obs>0)
            {
                cn.Open();

                cm = new SqlCommand("select COUNT(rollizo) from rollizos where categoria != 'rechazado'", cn);
                cant_acep = Convert.ToInt16(cm.ExecuteScalar());

                cm = new SqlCommand("select COUNT(rollizo) from rollizos where categoria = 'categoria1'", cn);
                cant_cat1 = Convert.ToInt16(cm.ExecuteScalar());

                cm = new SqlCommand("select COUNT(rollizo) from rollizos where categoria = 'categoria2'", cn);
                cant_cat2 = Convert.ToInt16(cm.ExecuteScalar());

                cm = new SqlCommand("select COUNT(rollizo) from rollizos where categoria = 'categoria3'", cn);
                cant_cat3 = Convert.ToInt16(cm.ExecuteScalar());

                cm = new SqlCommand("select COUNT(rollizo) from rollizos where categoria = 'rechazado'", cn);
                cant_rech = Convert.ToInt16(cm.ExecuteScalar());

                cm = new SqlCommand("select sum(volumen) from rollizos", cn);
                vol_obs = (Convert.ToDouble(cm.ExecuteScalar()))/1000;

                cm = new SqlCommand("select sum(volumen) from rollizos where categoria != 'rechazado'", cn);
                vol_acep = (Convert.ToDouble(cm.ExecuteScalar()))/1000;

                cm = new SqlCommand("select sum(volumen) from rollizos where categoria = 'categoria1'", cn);
                if (cm.ExecuteScalar() != DBNull.Value) { vol_cat1 = (Convert.ToDouble(cm.ExecuteScalar()))/1000; }

                cm = new SqlCommand("select sum(volumen) from rollizos where categoria = 'categoria2'", cn);
               if (cm.ExecuteScalar() != DBNull.Value) { vol_cat2 = (Convert.ToDouble(cm.ExecuteScalar()))/1000; }
                

                cm = new SqlCommand("select sum(volumen) from rollizos where categoria = 'categoria3'", cn);
                if (cm.ExecuteScalar() != DBNull.Value) { vol_cat3 = (Convert.ToDouble(cm.ExecuteScalar()))/1000; }

                cm = new SqlCommand("select sum(volumen) from rollizos where categoria = 'rechazado'", cn);
                if (cm.ExecuteScalar() != DBNull.Value) { vol_rech = (Convert.ToDouble(cm.ExecuteScalar()))/1000; }


                cn.Close();

            }

            text_cant_obs.Text = cant_obs.ToString();
            text_cant_acep.Text = cant_acep.ToString();
            text_cant_cat1.Text = cant_cat1.ToString();
            text_cant_cat2.Text = cant_cat2.ToString();
            text_cant_cat3.Text = cant_cat3.ToString();
            text_cant_rech.Text = cant_rech.ToString();

            text_vol_obs.Text  = vol_obs.ToString();
            text_vol_acep.Text = vol_acep.ToString();
            text_vol_cat1.Text = vol_cat1.ToString();
            text_vol_cat2.Text = vol_cat2.ToString();
            text_vol_cat3.Text = vol_cat3.ToString();
            text_vol_rech.Text = vol_rech.ToString();

            //c.cargainfo(dgvinfo);
            // ********************** ENTRADA DE DATOS **********************************
            rx = serialPort1.ReadLine();

                string[] datos = new string[3];
                datos = rx.Split(':');

            if (datos.Length==3)
            {
                int.TryParse(datos[0], out diam); 
                int.TryParse(datos[1], out laser1); 
                int.TryParse(datos[2], out laser2);

                diametro.Text = diam.ToString();
            }


// ************************ SELECCIÓN ***************************************
            if (diam > 0)
            {            
                pos=pos+1;
                suma_diam = suma_diam + diam;

                if (pos > 7)
                {
                    prom_diam = suma_diam / pos;
                    id_rollizo_text.Text = (cant_obs + 1).ToString();
                    float vol_est = PI * largo * (prom_diam * prom_diam) / 4;
                    prom_diam_text.Text = prom_diam.ToString();
                    vol_est_text.Text = vol_est.ToString();
                    flag2 = 1;

                    if (prom_diam >= 35 )
                    {
                        serialPort1.Write("1");
                        flag1 = 1;                       
                    }
                }
            }
            else
            {
               
                volumen = largo * PI * (prom_diam * prom_diam) / 4;
                
                if (flag1 == 1)
                {
                    categoria =  "rechazado";
                    this.Invoke((MethodInvoker)delegate
                    {
                        timer1.Enabled = true;
                    });
                    flag1 = 0;
                }

               if (prom_diam > 20 && prom_diam<=34)
               {
                    categoria = "categoria1";
                }
                if (prom_diam > 16 && prom_diam<=20)
                {
                    categoria = "categoria2";
                }

                if (prom_diam>0 && prom_diam<=16)
                {
                    categoria="categoria3";
                }

                if (categoria != "")
                {
                    cn.Open();
                    cmd = new SqlCommand("insert into rollizos(largo,diametro,volumen,categoria,fecha) values(" + largo + "," + prom_diam + "," + volumen + ",'" + categoria + "','" + fecha + "') ", cn);
                    cmd.ExecuteNonQuery();
                    cn.Close();
                }

                suma_diam = 0;
                prom_diam = 0;
                pos = 0;
                if (flag2 == 1)
                {
                    clasif_text.Text = categoria;
                    flag2 = 0;
                }

                categoria = "";
            }

// ********************** CLASIFICACIÓN ************************************

            if (laser1 == 1) // PRIMER LASER
            {
                cont2++;
                if (cont2 == 5)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        timer2.Enabled = true;
                        serialPort1.Write("3");
                    });
                }
            }
            else { cont2 = 0; }

            if (laser2 == 1) // SEGUNDO LASER
            {
                cont3++;
                if (cont3 == 5)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        timer3.Enabled = true;
                        serialPort1.Write("5");
                    });
                }
            }
            else { cont3 = 0; }


            graph1.ChartAreas[0].Area3DStyle.Enable3D = true;

            if (graph1.Series[0].Points.Count > 20)
            {
                graph1.Series[0].Points.RemoveAt(0);
                graph1.Update();
            }
            graph1.Series[0].Points.AddXY(x_graph, diam);


            


        }

        // *********************** TIMER 1 *****************************************
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            cont1 = 0;
            serialPort1.Write("0");
        }


        // *********************** TIMER 2 *****************************************
        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            cont2 = 0;
            serialPort1.Write("2");
        }

        // *********************** TIMER 3 *****************************************
        private void timer3_Tick(object sender, EventArgs e)
        {
            timer3.Enabled = false;
            cont3 = 0;
            serialPort1.Write("4");
        }

        private void vec_Click(object sender, EventArgs e)
        {

        }

        private void boton_rep_Click(object sender, EventArgs e)
        {
            Form Form_reporte = new Form_reporte();
            Form_reporte.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                if (flag_a1 == 0)
                {
                    serialPort1.Write("1");
                    flag_a1 = 1;
                    act1.Text = "Desactivar";
                }
                else
                {
                    serialPort1.Write("0");
                    flag_a1 = 0;
                    act1.Text = "Activar";

                }
            }
            else { MessageBox.Show("NO SE HA DETECTADO CONEXIÓN"); }
        }

        private void act2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                if (flag_a2 == 0)
                {
                    serialPort1.Write("3");
                    flag_a2 = 1;
                    act2.Text = "Desactivar";
                }
                else
                {
                    serialPort1.Write("2");
                    flag_a2 = 0;
                    act2.Text = "Activar";

                }
            }
            else { MessageBox.Show("NO SE HA DETECTADO CONEXIÓN"); }
        }

        private void act3_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                if (flag_a3 == 0)
                {
                    serialPort1.Write("5");
                    flag_a3 = 1;
                    act3.Text = "Desactivar";
                }
                else
                {
                    serialPort1.Write("4");
                    flag_a3 = 0;
                    act3.Text = "Activar";

                }
            }
            else { MessageBox.Show("NO SE HA DETECTADO CONEXIÓN"); }
        }
    }
}
