using System;
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.IO;
using System.Reflection;


namespace zapisovac
{
    
    public partial class Form1 : Form
    {

       
        
        Pen P = new Pen(Color.Blue, 2);
        bool pausePress = false, hore = false, dole = false, levo = false, pravo = false, vypnoutKom = true, startPress = false, stopPress = false, posunX = false, posunY = false;
        UInt16   xPos = 0, yPos = 0, velBod = 6;
        
        int[] data1 = new int[590];
        int[] data2 = new int[590];
        int[] data3 = new int[590];
        int[] data4 = new int[590];
        int[] data5 = new int[590];
        int[] data6 = new int[590];

        int lehoKvadrant = 0, ledoKvadrant = 0, prhoKvadrant = 0, prdoKvadrant = 0, nasobPrev = 1;
        FileInfo fi = new FileInfo(Path.Combine(Environment.CurrentDirectory, "vysledek_mereni.csv"));
        FileInfo fi2 = new FileInfo(Path.Combine(Environment.CurrentDirectory, "vysledek_mereni_chyba.csv"));        
        public Form1()
        {  
  
           InitializeComponent();
               
        }

         
        private void ErrorYposunB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
                posunY = true;
            
        }
        private void ErrorXposunB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
                posunX = true;
       
        }
        private void NahoruB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
            {
                hore = true;
                spodlab1.ForeColor = Color.Black;
                spodlab1.Text = "Manuální hledání paprsku";
            }
           
        }

        private void DoluB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
            {
                dole = true;
                spodlab1.ForeColor = Color.Black;
                spodlab1.Text = "Manuální hledání paprsku";
            }
           
        }

        private void LevoB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
            {
                levo = true;
                spodlab1.ForeColor = Color.Black;
                spodlab1.Text = "Manuální hledání paprsku";
            }
           
        }

        private void PravoB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
            {
                pravo = true;
                spodlab1.ForeColor = Color.Black;
                spodlab1.Text = "Manuální hledání paprsku";
            }
          
        }

        private void KomunBut_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Spustit komunikaci")
            {
                
                vypnoutKom = false;
                serialPort1.PortName = portVyb.Text;
                serialPort1.BaudRate = 250000;
                
                Thread komunikace = new Thread(spustse);
                komunikace.Start();
            }

            if (KomBut.Text == "Vypnout komunikaci")
            {
                vypnoutKom = true;
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            pausePress = true;
           
        }
        
        private void StartB_Click(object sender, EventArgs e)
        {
            if (KomBut.Text == "Vypnout komunikaci")
            startPress = true;
        }

        private void StopB_Click(object sender, EventArgs e)
        {
            stopPress = true;
        }



        // funkce na pozadi
        void spustse()
        {    
            bool chyba=false;
           
            EnabForm(false);
                                  

            try
            {
                
                if (!serialPort1.IsOpen)
                    serialPort1.Open();
                serialPort1.Write("p");
                StavRadek2W("Komunikační rychlost: 250 kBaud", false);

                Tlkomun(false);

                while (true)
                {

                    if (posunY)
                    {
                        posunY = false;
                        serialPort1.Write("y");
                        Thread.Sleep(20);
                    }
                    if (posunX)
                    {
                        posunX = false;
                        serialPort1.Write("x");
                        Thread.Sleep(20);
                    }
                    
                    if (levo)
                    {
                        levo = false;
                        serialPort1.Write("<");
                        Thread.Sleep(20);
                    }

                    if (pravo)
                    {
                        pravo = false;
                        serialPort1.Write(">");
                        Thread.Sleep(20);
                    }

                    if (hore)
                    {
                        hore = false;
                        serialPort1.Write("n");
                        Thread.Sleep(20);
                    }

                    if (dole)
                    {
                        dole = false;
                        serialPort1.Write("d");
                        Thread.Sleep(20);
                    }
                    
                    if (stopPress)
                    {
                        EnabStart(true);
                        EnabStop(false);
                        EnabPause(false);
                        stopPress = false;
                       

                        serialPort1.Write("k");
                        Thread.Sleep(1);
                    }

                    if (startPress)
                    {
                       
                        EnabStart(false);
                        EnabStop(true);
                        EnabPause(true);
                        startPress = false;
                        StavRadek1W("Zaměřování", true);
                        serialPort1.Write("g");
                        serialPort1.Write("s");
                        Thread.Sleep(1);
                    }

                    if (pausePress)
                    {
                        
                        EnabStart(true);
                        EnabStop(true);
                        EnabPause(false);
                        pausePress = false;
                        StavRadek1W("Pause", true);
                        serialPort1.Write("p");
                        Thread.Sleep(1);
                    }


                    if (serialPort1.BytesToRead > 0)    // cekani na znackovy bit
                    {

                        switch (serialPort1.ReadByte())
                        {
                            case 'Z':                                   //poslána zpráva
                                while (serialPort1.BytesToRead < 13)
                                    Thread.Sleep(1);
                                chyba = false;  
                            //potvrzeni = true;
                                if ((xPos = cti()) > 2300)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }                          //cteni pozice
                                
                                if ((yPos = cti()) > 2300)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }
                                
                                nasobPrev = serialPort1.ReadByte();     //cteni nasobicky

                                if ((lehoKvadrant = cti()) > 1024)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }
                                
                                if ((ledoKvadrant = cti()) > 1024)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }
                                
                                if ((prhoKvadrant = cti()) > 1024)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }
                                
                                if ((prdoKvadrant = cti()) > 1024)
                                {
                                    serialPort1.Write("e");
                                    chyba = true;
                                }
                                serialPort1.DiscardInBuffer();
                                serialPort1.Write("g");
                                UlozitDoSouboru2(xPos.ToString() + ";" + yPos.ToString() + ";" + (lehoKvadrant).ToString() + ";" + (ledoKvadrant).ToString() + ";" + (prhoKvadrant).ToString() + ";" + (prdoKvadrant).ToString() + ";" + (nasobPrev).ToString());
                                if (!chyba)
                                {
                                    UlozitDoSouboru(xPos.ToString() + ";" + yPos.ToString() + ";" + (lehoKvadrant).ToString() + ";" + (ledoKvadrant).ToString() + ";" + (prhoKvadrant).ToString() + ";" + (prdoKvadrant).ToString() + ";" + (nasobPrev).ToString());

                                    LHbarW(lehoKvadrant / nasobPrev * 2);             //cteni bargrafu
                                  LDbarW(ledoKvadrant/nasobPrev*2);
                                  PHbarW(prhoKvadrant/nasobPrev*2);
                                  PDbarW(prdoKvadrant/nasobPrev*2);
                                  
                                    Prefres();                          //zapis do grafu
                                    Prefres2();
                                    Prefres3();
                                    Prefres4();
                                    Prefres5();
                                    Prefres6();
                                    Prefres7();
                                    
                                }
                                 
                                    break;

                            case 'N':                                   //paprsek nenalezen

                                StavRadek2W("Nenalezen paprsek", true);
                               
                                break;
                              
                             case 'H':
                                 StavRadek1W("Při posouvání překročeny hranice", true);
                                 break;
                                
                            case 'P':
                                 EnabStart(true);
                                 EnabStop(false);
                                 EnabPause(false);
                                 StavRadek1W("Sledovani zastaveno", true);


                                 break;
                                   
                            case 'S':
                                StavRadek1W("Spusteno sledovani", false);
                                break;

                            default:
                                Thread.Sleep(1);
                                serialPort1.DiscardInBuffer();
                                serialPort1.Write("e");
                                serialPort1.Write("g");
                                break;
                        }
                       
                    }
                    if (vypnoutKom == true)
                    {
                        serialPort1.Close();
                        EnabStart(true);
                        EnabStop(false);
                        Tlkomun(true);
                        EnabForm(true);
                        StavRadek1W("Komunikace ukoncena", false);
                        break;
                    }
                }

            }

            catch
            {
               // serialPort1.Write("p");
                serialPort1.Close();
                EnabStart(true);
                EnabStop(false);
                Tlkomun(true);
                EnabForm(true);
                StavRadek1W("No device detected on this port",true);
                Thread.Sleep(500);
                StavRadek2W("Komunikace uzavřena chybou přenosu či dat", true);
                
            }
        }

        UInt16 cti()
        {
            byte[] mala = new byte[2];                  // alokace pameti
            if (serialPort1.BytesToRead >= 2)           //podminka dvou zbyvajiich bytu
            {
                serialPort1.Read(mala, 0, 2);           //precteni dvou bytu
                return (BitConverter.ToUInt16(mala, 0));//spojeni dvou bytu do cisla
            }
            else return (0xffff);
        }

       
        
        void Tlkomun (bool start)       //prepisovani spojovaciho tlacitka
        {
            if (KomBut.InvokeRequired)
            {
                KomBut.Invoke(new MethodInvoker(delegate()
                {
                    Tlkomun (start);
                }));
                return;
            }

            if (start) KomBut.Text = "Spustit komunikaci";
            else KomBut.Text = "Vypnout komunikaci";

        }

        void EnabForm (bool enableB)       // schovavani tlacitka s vyberem portu
        {
            if (portVyb.InvokeRequired)
            {
                portVyb.Invoke(new MethodInvoker(delegate()
                {
                    EnabForm(enableB);
                }));
                return;
            }
            portVyb.Enabled = enableB;
        }

        void LDbarW(Int32 hodnota)         // zapis na bar LD
        {
            if (BarLD.InvokeRequired)
            {
                BarLD.Invoke(new MethodInvoker(delegate()
                {
                    LDbarW(hodnota);
                }));
                return;
            }
            BarLD.Value = hodnota;
        }

        void LHbarW(Int32 hodnota)         // zapis na bar LH
        {
            if (BarLH.InvokeRequired)
            {
                BarLH.Invoke(new MethodInvoker(delegate()
                {
                    LHbarW(hodnota);
                }));
                return;
            }
            BarLH.Value = hodnota;
        }
        
        void PDbarW(Int32 hodnota)         // zapis na bar PD
        {
            if (BarPD.InvokeRequired)
            {
                BarPD.Invoke(new MethodInvoker(delegate()
                {
                    PDbarW(hodnota);
                }));
                return;
            }
            BarPD.Value = hodnota;
        }

        void PHbarW(Int32 hodnota)         // zapis na bar PH
        {
            if (BarPH.InvokeRequired)
            {
                BarPH.Invoke(new MethodInvoker(delegate()
                {
                    PHbarW(hodnota);
                }));
                return;
            }
            BarPH.Value = hodnota;
        }

        void EnabStart(bool enableB)       // schovavani tlacitka start
        {
            if ( StartB.InvokeRequired)
            {
                StartB.Invoke(new MethodInvoker(delegate()
                {
                    EnabStart(enableB);
                }));
                return;
            }
            StartB.Enabled = enableB;
        }

        void EnabPause(bool enableB)       // schovavani tlacitka start
        {
            if (PauseB.InvokeRequired)
            {
                PauseB.Invoke(new MethodInvoker(delegate()
                {
                    EnabPause(enableB);
                }));
                return;
            }
            PauseB.Enabled = enableB;
        }

        void EnabStop(bool enableB)       // schovavani tlacitka stop
        {
            if (StopB.InvokeRequired)
            {
                StopB.Invoke(new MethodInvoker(delegate()
                {
                    EnabStop(enableB);
                }));
                return;
            }
            StopB.Enabled = enableB;
        }

                    
        void StavRadek1W(string textW, bool zvyraznit)       // zapis do prvniho prvku ve stav radku
        {
            if (StatRad.InvokeRequired)
            {
                StatRad.Invoke(new MethodInvoker(delegate()
                {
                    StavRadek1W (textW, zvyraznit);
                }));
                return;
            }
            spodlab1.Text = textW;
            if (zvyraznit) spodlab1.ForeColor = Color.Red;
            else spodlab1.ForeColor = Color.Black;
        }

        void StavRadek2W(string textW, bool zvyraznit)       // zapis do prvniho prvku ve stav radku
        {
            if (StatRad.InvokeRequired)
            {
                StatRad.Invoke(new MethodInvoker(delegate()
                {
                    StavRadek2W(textW, zvyraznit);
                }));
                return;
            }
            spodlab1.Text = textW;
            if (zvyraznit) spodlab1.ForeColor = Color.Red;
            else spodlab1.ForeColor = Color.Black;
        }

        void Prefres()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox.InvokeRequired)
            {
                picBox.Invoke(new MethodInvoker(delegate()
                {
                    Prefres();
                }));
                return;
            }
            picBox.Refresh();
        }
        
        
        
        
        void Prefres2()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox2.InvokeRequired)
            {
                picBox2.Invoke(new MethodInvoker(delegate()
                {
                    Prefres2();
                }));
                return;
            }
            picBox2.Refresh();
        }
        
        
        
        
        
        
        void Prefres3()       // zapis do prvniho prvku ve stav radku
        {    
        if (picBox3.InvokeRequired)
            {
                picBox3.Invoke(new MethodInvoker(delegate()
                {
                    Prefres3();
                }));
                return;
            }
            picBox3.Refresh();
              
        
        }
        void Prefres4()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox4.InvokeRequired)
            {
                picBox4.Invoke(new MethodInvoker(delegate()
                {
                    Prefres4();
                }));
                return;
            }
            picBox4.Refresh();


        }
        void Prefres5()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox5.InvokeRequired)
            {
                picBox5.Invoke(new MethodInvoker(delegate()
                {
                    Prefres5();
                }));
                return;
            }
            picBox5.Refresh();


        }
        void Prefres6()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox6.InvokeRequired)
            {
                picBox6.Invoke(new MethodInvoker(delegate()
                {
                    Prefres6();
                }));
                return;
            }
            picBox6.Refresh();


        }
        void Prefres7()       // zapis do prvniho prvku ve stav radku
        {
            if (picBox7.InvokeRequired)
            {
                picBox7.Invoke(new MethodInvoker(delegate()
                {
                    Prefres7();
                }));
                return;
            }
            picBox7.Refresh();


        }
        
        private void picBox_Paint(object sender, PaintEventArgs e)
        {  // barva = new (Brushes.Red);
            //barva = Brushes.Green;
            if (nasobPrev == 200) velBod = 5 ;
            if (nasobPrev == 100) velBod = 6;
            if (nasobPrev == 50) velBod = 7;
            if (nasobPrev == 20) velBod = 8;
            if (nasobPrev == 10) velBod = 9;
            if (nasobPrev == 5) velBod = 10;
            if (nasobPrev == 2) velBod = 12;
            if (nasobPrev == 1) velBod = 14;

            e.Graphics.FillEllipse (Brushes.Red, xPos * (picBox.Width-velBod-3) /2200, yPos * (picBox.Height-velBod-3) / 2200, velBod, velBod);
            
                       
            
           
        }

        private void picBox2_Paint(object sender, PaintEventArgs e)
        {
                e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
                e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
                e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
                e.Graphics.DrawLine(Pens.Black, 5, 118, 0, 113);
                e.Graphics.DrawLine(Pens.Black, 5, 118, 10, 113);
                e.Graphics.DrawLine(Pens.Black, 0, 59, 10, 59);
                
                for (int j = 589; j > 0; j--)
                {
                    data1[j] = data1[j - 1];
                }
                data1[0] = xPos;
                for (int i = 0; i < 589 ; i++)
                {
                    //e.Graphics.FillEllipse(Brushes.Blue, i,  (data1[i] * 120 / 2200) , velBod3, velBod3);
                    e.Graphics.DrawLine(Pens.Blue, i, data1[i] * 120 / 2200, i + 1,  data1[i + 1] * 120 / 2200);

                }
          
           
        }
        private void picBox3_Paint(object sender, PaintEventArgs e)
        {

            e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 5, 118, 0, 113);
            e.Graphics.DrawLine(Pens.Black, 5, 118, 10, 113);
            e.Graphics.DrawLine(Pens.Black, 0, 59, 10, 59);

                for (int j = 589; j > 0; j--)
                {
                    data2[j] = data2[j - 1];
                }
                data2[0] = yPos;
                for (int i = 0; i < 589; i++)
                {
                    e.Graphics.DrawLine(Pens.Blue, i,  data2[i] * 120 / 2200, i + 1,  data2[i + 1] * 120 / 2200);
                    //e.Graphics.FillEllipse(Brushes.Black, i, (data2[i] * 120 / 2200) , velBod3, velBod3);
                }
          
        }

        private void picBox4_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
           

            for (int j = 589; j > 0; j--)
            {
                data3[j] = data3[j - 1];
            }
            data3[0] = lehoKvadrant / nasobPrev*2 ;
            for (int i = 0; i < 589 ; i++)
            {
                //e.Graphics.FillEllipse(Brushes.Blue, i,115- (data3[i] * 120 / 1024), velBod3, velBod3);
                e.Graphics.DrawLine(Pens.Blue, i, 117 - data3[i] * 120 / 1024 , i + 1, 117 - data3[i + 1] * 120 / 1024);

            }
        }

        private void picBox5_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
           

            for (int j = 589; j > 0; j--)
            {
                data4[j] = data4[j - 1];
            }
            data4[0] = ledoKvadrant / nasobPrev*2 ;
            for (int i = 0; i < 589 ; i++)
            {
                //e.Graphics.FillEllipse(Brushes.Blue, i, 115-(data4[i] * 120 / 1024), velBod3, velBod3);
                e.Graphics.DrawLine(Pens.Blue, i, 117 - data4[i] * 120 / 1024 , i + 1, 117 - data4[i + 1] * 120 / 1024 );

            }
        }

        private void picBox6_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
           

            for (int j = 589; j > 0; j--)
            {
                data5[j] = data5[j - 1];
            }
            data5[0] = prhoKvadrant / nasobPrev*2 ;
            for (int i = 0; i < 589; i++)
            {
                //e.Graphics.FillEllipse(Brushes.Blue, i,115-(data5[i] * 120 / 1024), velBod3, velBod3);
                e.Graphics.DrawLine(Pens.Blue, i, 117 - data5[i] * 120 / 1024 , i + 1, 117 - data5[i + 1] * 120 / 1024);

            }
        }

        private void picBox7_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(Pens.Black, 5, 120, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 0, 5, 5, 0);
            e.Graphics.DrawLine(Pens.Black, 10, 5, 5, 0);
           

            for (int j = 589; j > 0; j--)
            {
                data6[j] = data6[j - 1];
            }
            data6[0] = prdoKvadrant / nasobPrev*2 ;
            for (int i = 0; i < 589 ; i++)
            {
                //e.Graphics.FillEllipse(Brushes.Blue, i, 115-(data6[i] * 120 / 1024), velBod3, velBod3);
                e.Graphics.DrawLine(Pens.Blue, i, 117 - data6[i] * 120 / 1024 , i + 1, 117 - data6[i + 1] * 120 / 1024 );

          }
        }

        public void UlozitDoSouboru(string sb)
        {
            StreamWriter sw = fi.AppendText(); 
           
            sw.WriteLine(sb);
            sw.Close();
            fi.Refresh();
           
 
        }

        public void UlozitDoSouboru2(string sb)
        {
            StreamWriter sw = fi2.AppendText();

            sw.WriteLine(sb);
            sw.Close();
            fi.Refresh();
            

        }
        
    } 
}
