using System;
using System.IO.Ports;
using System.IO;
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.Net;
using System.Net.Sockets;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectInput;
using CsharpUSBJoystick;

namespace Ovladani_voziku
{
    public partial class Form1 : Form
    {
        USB_Joystick joystick;
        const int ROZSAH_JOYSTICKU = 255, STRANA_PAINTBOXU = 150;
        bool RizeniPovoleno = false;
        private UdpClient prichoziKlient,odchoziKlient;
        protected byte[] prijataData;
        protected object oKlic = new object();

        Byte FLVzdalenost = 255, FRVzdalenost = 255, RLVzdalenost = 255, RRVzdalenost = 255;

        enum smeryJoysticku : byte { LN = 1, N, PN, L, STOP, P, LD, D, PD };       //enum - smer vychyleni joysticku
        byte smerJoysticku = (byte)smeryJoysticku.STOP;     //smer vychyleni

        public Form1()
        {
            InitializeComponent();
            odchoziKlient = new UdpClient();
            prichoziKlient = new UdpClient(Convert.ToInt32(labelPrichoziPort.Text));

            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());     //ziska lokalni hostitelske adresy
            textBoxIP.Text = labelPrichoziIP.Text = localIPs[0].ToString();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try     //inicializace instance tridy USB_Joystick
            {   
                joystick = new USB_Joystick(0,ROZSAH_JOYSTICKU,0.2,this);

                joystick.PresetValues();
                joystick.GetData();
                VykresliPoziciJoysticku();

                timerJoystick.Start();
            }
            catch (Exception) {
                MessageBox.Show("Nebylo možno inicializovat joystick", "Pozor!", MessageBoxButtons.OK);

                buttonSTART.Enabled = false;
                buttonJoysticPripojeniRefresh.Visible = true;   //zviditelni tlacitko, umoznujici znovupripojeni joysticku
            }

            prichoziKlient.BeginReceive(CallbackPrijmi, this);
        }

        protected static void CallbackPrijmi(IAsyncResult IAR)
        {
            Form1 tempForm = (Form1)(IAR.AsyncState);
            IPEndPoint IPep = new IPEndPoint(0, 0);

            try
            {
                Byte[] prijataData = tempForm.prichoziKlient.EndReceive(IAR, ref IPep);  // ukončení přijímání a uložení přijatých dat do bufferu (ep - end point = adresa a port od koho zpráva přišla)

                lock (tempForm.oKlic)                                            // zamknu data pro ostatní vlákna
                {
                    tempForm.prijataData = prijataData;
                }
            }
            catch (System.Net.Sockets.SocketException exception)
            {
                MessageBox.Show(exception.Message.ToString() + ".", "Vyjímka SocketException!", MessageBoxButtons.OK);
            }

        }

        private void timer1_Tick(object sender, EventArgs e)        //vyhodnoti pohyb joysticku, prekresli grafiku a odesle data pres wifi
        {
            byte[] data = new byte[3];  //trida UdpClient vyzaduje data typu byte[]
            int tempX, tempY, tempZ, tempZred;

            joystick.GetData();

            tempX = joystick.State.X;
            tempY = joystick.State.Y;
            tempZ = joystick.State.Z;

            if (JoystickXUvnitrThreshold(tempX) == true)       //kontrolka thresholdu osy X
                pictureBoxThresholdX.BackColor = Color.LimeGreen;
            else
                pictureBoxThresholdX.BackColor = Color.White;

            if (JoystickYUvnitrThreshold(tempY) == true)       //kontrolka thresholdu osy Y
                pictureBoxThresholdY.BackColor = Color.LimeGreen;
            else
                pictureBoxThresholdY.BackColor = Color.White;

            #region Smer
            //urcuje zamysleny smer voziku dle polohy joysticku

            if ((JoystickXUvnitrThreshold(tempX) || JoystickYUvnitrThreshold(tempY)) == false)
            {
                if (tempX < 127)
                {
                    if (tempY < 127)
                        smerJoysticku = (byte)smeryJoysticku.LN;
                    else
                        smerJoysticku = (byte)smeryJoysticku.LD;
                }
                else
                {
                    if (tempY < 127)
                        smerJoysticku = (byte)smeryJoysticku.PN;
                    else
                        smerJoysticku = (byte)smeryJoysticku.PD;
                }
            }
            else
            {
                if (JoystickXUvnitrThreshold(tempX))
                {
                    if (tempY < 127)
                        smerJoysticku = (byte)smeryJoysticku.N;
                    else
                        smerJoysticku = (byte)smeryJoysticku.D;

                    if (JoystickYUvnitrThreshold(tempY))
                        smerJoysticku = (byte)smeryJoysticku.STOP;
                }
                else
                {
                    if (tempX < 127)
                        smerJoysticku = (byte)smeryJoysticku.L;
                    else
                        smerJoysticku = (byte)smeryJoysticku.P;
                }
            }

            switch (smerJoysticku)
            {
                case 1: labelSmer.Text = "Směr:\nLN"; break;
                case 2: labelSmer.Text = "Směr:\nN"; break;
                case 3: labelSmer.Text = "Směr:\nPN"; break;
                case 4: labelSmer.Text = "Směr:\nL"; break;
                default: labelSmer.Text = "Směr:\nN/A"; break;
                case 6: labelSmer.Text = "Směr:\nP"; break;
                case 7: labelSmer.Text = "Směr:\nLD"; break;
                case 8: labelSmer.Text = "Směr:\nD"; break;
                case 9: labelSmer.Text = "Směr:\nPD"; break;
            }

            #endregion

            #region UpravaGainu
            //snizuje gain podle dat z UZ senzoru

            byte tempFL, tempFR, tempRR, tempRL;

            tempFL = (FLVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text)) ? (byte)(255 * ((float)(FLVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))) : (byte)255;    //plynule snizovani gainu, pokud je detekovan objekt ve sledovane vzdalenosti
            tempFR = (FRVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text)) ? (byte)(255 * ((float)(FRVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))) : (byte)255;
            tempRL = (RLVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text)) ? (byte)(255 * ((float)(RLVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))) : (byte)255;
            tempRR = (RRVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text)) ? (byte)(255 * ((float)(RRVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))) : (byte)255;

            if (FLVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))  //pokud je objekt blize, nez kriticka vzdalenost, stahne gain na 0
                tempFL = 0;
            if (FRVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                tempFR = 0;
            if (RRVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                tempRR = 0;
            if (RLVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                tempRL = 0;


            switch (smerJoysticku)
            {
                case 1: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * (tempFL / 255.0)); break;
                case 2: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * ((tempFL < tempFR ? tempFL : tempFR) / 255.0)); break;
                case 3: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * (tempFR / 255.0)); break;
                case 4: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * ((tempFL < tempRL ? tempFL : tempRL) / 255.0)); break;
                default: tempZred = ROZSAH_JOYSTICKU - tempZ; break;
                case 6: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * ((tempFR < tempRR ? tempFR : tempRR) / 255.0)); break;
                case 9: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * (tempRL / 255.0)); break;     //pri vychyleni joysticku smerem LD se vozik staci smerem PD
                case 8: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * ((tempRL < tempRR ? tempRL : tempRR) / 255.0)); break;
                case 7: tempZred = (int)((ROZSAH_JOYSTICKU - tempZ) * (tempRR / 255.0)); break;     //prohozeni se smerem LD, viz. vyse
            }


            #endregion

            VykresliPoziciJoysticku(ref data, tempX, tempY, tempZ, tempZred);  //vykresli pozici a prijme pole hodnot X,Y,Z

            if (RizeniPovoleno == true)
            {
                odchoziKlient.Send(data, data.Length, textBoxIP.Text, Convert.ToInt32(textBoxPort.Text));  //odesle data pres wifi
                tiskniCas();
                textBoxLog.AppendText("Odesláno:" + data[0].ToString() + " " + data[1].ToString() + " " + data[2].ToString() + Environment.NewLine);
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)     //vykresluje pozicni kriz
        {
            Graphics platno = e.Graphics;
            Pen pero = new Pen(Color.Black),pero2 =new Pen(Color.OrangeRed,4f);

            try
            {
                //osa z
                platno.DrawLine(pero2, STRANA_PAINTBOXU - pero2.Width, STRANA_PAINTBOXU, STRANA_PAINTBOXU - pero2.Width,
                        (float)((joystick.State.Z / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU));
                //vodorovna linka pozicniho krize
                platno.DrawLine(pero, (float)((joystick.State.X / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU) - 5, (float)((joystick.State.Y / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU),
                        (float)((joystick.State.X / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU) + 5, (float)((joystick.State.Y / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU));
                //svisla linka pozicniho krize
                platno.DrawLine(pero, (float)((joystick.State.X / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU), (float)((joystick.State.Y / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU) - 5,
                        (float)((joystick.State.X / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU), (float)((joystick.State.Y / (float)ROZSAH_JOYSTICKU) * STRANA_PAINTBOXU) + 5);
            }
            catch(System.NullReferenceException)
            {
                platno.DrawString("Error", new Font("Arial", 22), new SolidBrush(Color.Red), 0f, 0f);
            }

        }

        private void tiskniCas()       //tiskne cas do logu
        {
            textBoxLog.AppendText(DateTime.Now.Hour.ToString()+":"+DateTime.Now.Minute.ToString()+":"+DateTime.Now.Second.ToString()+" ");
        }

        private void buttonVymazLog_Click(object sender, EventArgs e)
        {
            textBoxLog.Clear();
        }

        private void VykresliPoziciJoysticku(ref byte[] data, int tempX, int tempY, int tempZ, int tempZred)  //vykresli hodnoty prectene z joysticku na progressbary, referenci preda pole hodnot X,Y,Z
        {
                joystick.GetData();

                progressBarX.Value = tempX;
                progressBarY.Value = ROZSAH_JOYSTICKU - tempY;
                progressBarZ.Value = ROZSAH_JOYSTICKU - tempZ;
                progressBarZred.Value = tempZred;
                labelX.Text = (tempX).ToString();
                labelY.Text = (ROZSAH_JOYSTICKU - tempY).ToString();
                labelZ.Text = (ROZSAH_JOYSTICKU - tempZ).ToString();
                labelZred.Text = tempZred.ToString();

                pictureBoxPoziceJoysticku.Refresh();

                data[0] = (byte)joystick.State.X;   //nacteni hodnot os joysticku
                data[1] = (byte)joystick.State.Y;
                data[2] = (byte)joystick.State.Z;
        }

        private void VykresliPoziciJoysticku()  //vykresli hodnoty prectene z joysticku na progressbary
        {
            joystick.GetData();

            progressBarX.Value = joystick.State.X;
            progressBarY.Value = ROZSAH_JOYSTICKU - joystick.State.Y;
            progressBarZred.Value = progressBarZ.Value = ROZSAH_JOYSTICKU - joystick.State.Z;
            labelX.Text = (joystick.State.X).ToString();
            labelY.Text = (ROZSAH_JOYSTICKU - joystick.State.Y).ToString();
            labelZred.Text = labelZ.Text = (ROZSAH_JOYSTICKU - joystick.State.Z).ToString();

            pictureBoxPoziceJoysticku.Refresh();
        }

        private void buttonSTART_Click(object sender, EventArgs e)
        {
            if (buttonSTART.Text == "START")
            {
                buttonSTART.Text = "STOP";
                RizeniPovoleno = true;
            }
            else 
            {
                buttonSTART.Text = "START";
                RizeniPovoleno = false;
            }
        }

        private void timerObraz_Tick(object sender, EventArgs e)
        {
            if (prijataData != null)
            {
                Image frame;
                Graphics grafika = pictureBoxWebkamera.CreateGraphics();
                Int32 Uhel;

                lock (oKlic)            //zamkne data pro ostatni thready
                {
                    if (prijataData[0] == 2 || prijataData[0] == 3) //pokud jsou platna data z UZ senzoru
                    {
                        FLVzdalenost = Convert.ToByte(textBoxFLVzdalenost.Text = prijataData[1].ToString());
                        FRVzdalenost = Convert.ToByte(textBoxFRVzdalenost.Text = prijataData[2].ToString());
                        RRVzdalenost = Convert.ToByte(textBoxRRVzdalenost.Text = prijataData[3].ToString());
                        RLVzdalenost = Convert.ToByte(textBoxRLVzdalenost.Text = prijataData[4].ToString());

                        Uhel = prijataData[5] + (prijataData[6] << 8);

                        textBoxSledovanaVzdalenost.Text = prijataData[8].ToString();    //nastaveni kriticke a sledovane vzdalenosti
                        textBoxKritickaVzdalenost.Text = prijataData[9].ToString();  

                        VykresliOrientaciVoziku(Uhel);
                    }
                    else
                    {
                        FLVzdalenost = Convert.ToByte(textBoxFLVzdalenost.Text = "255");
                        FRVzdalenost = Convert.ToByte(textBoxFRVzdalenost.Text = "255");
                        RRVzdalenost = Convert.ToByte(textBoxRRVzdalenost.Text = "255");
                        RLVzdalenost = Convert.ToByte(textBoxRLVzdalenost.Text = "255");

                        pictureBoxOrientaceVoziku.Refresh();

                        Graphics platno = pictureBoxOrientaceVoziku.CreateGraphics();
                        platno.DrawString("Data UZ nejsou k dispozici", new Font("Arial", 14.0f), new SolidBrush(Color.Red), new Point(10, (pictureBoxOrientaceVoziku.Height / 2)-7));
                    }

                    textBoxThreasholdPerc.Text = prijataData[7].ToString();     //velikost pasma necitlivosti
                        

                    if (prijataData[0] == 1 || prijataData[0] == 3) //pokud se prijima obraz
                    {
                        MemoryStream ms = new MemoryStream(prijataData, 10, prijataData.Length - 10);

                        frame = Image.FromStream(ms);   //ziska frame z prichozich dat
                        grafika.DrawImage(frame, 0, 0, pictureBoxWebkamera.Width, pictureBoxWebkamera.Height);      //vykresli frame s rozmery pictureboxu
                    }
                    else
                    {
                        grafika.Clear(Color.White);
                        grafika.DrawString("Obraz není k dispozici", new Font("Arial", 16.0f), new SolidBrush(Color.Red), new Point(50, (pictureBoxWebkamera.Height / 2)-8));
                    }

                    prijataData = null;
                }
                prichoziKlient.BeginReceive(CallbackPrijmi, this);  //obnovi odposlech
            }
        }

        private void buttonZacitPrijimat_Click(object sender, EventArgs e)
        {
            if (timerObraz.Enabled == false)
            {
                timerObraz.Enabled = true;
                buttonZacitPrijimat.Text = "Ukončit příjem";
            }
            else
            {
                timerObraz.Enabled = false;
                buttonZacitPrijimat.Text = "Začít přijímat";            
            }
        }

        private void VykresliOrientaciVoziku(Int32 Uhel)
        {
            Color barvaFL, barvaFR, barvaRL, barvaRR;

            if (FLVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text))
            {
                if (FLVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                    barvaFL = Color.Red;
                else
                    barvaFL = Color.FromArgb(255 - (int)(255 * ((float)(FLVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))), 255, 0);   //prechod zelena->zluta dle vzdalenosti
            }
            else
                barvaFL = Color.FromArgb(0, 255, 0);

            if (FRVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text))
            {
                if (FRVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                    barvaFR = Color.Red;
                else
                    barvaFR = Color.FromArgb(255 - (int)(255 * ((float)(FRVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))), 255, 0);   //prechod zelena->zluta dle vzdalenosti
            }
            else
                barvaFR = Color.FromArgb(0, 255, 0);

            if (RLVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text))
            {
                if (RLVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                    barvaRL = Color.Red;
                else
                    barvaRL = Color.FromArgb(255 - (int)(255 * ((float)(RLVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))), 255, 0);   //prechod zelena->zluta dle vzdalenosti
            }
            else
                barvaRL = Color.FromArgb(0, 255, 0);

            if (RRVzdalenost <= Convert.ToByte(textBoxSledovanaVzdalenost.Text))
            {
                if (RRVzdalenost <= Convert.ToByte(textBoxKritickaVzdalenost.Text))
                    barvaRR = Color.Red;
                else
                    barvaRR = Color.FromArgb(255 - (int)(255 * ((float)(RRVzdalenost - Convert.ToByte(textBoxKritickaVzdalenost.Text)) / (float)(Convert.ToByte(textBoxSledovanaVzdalenost.Text) - Convert.ToByte(textBoxKritickaVzdalenost.Text)))), 255, 0);   //prechod zelena->zluta dle vzdalenosti
            }
            else
                barvaRR = Color.FromArgb(0, 255, 0);

            Bitmap bitmapaTemp = new Bitmap(pictureBoxOrientaceVoziku.Width, pictureBoxOrientaceVoziku.Height);     //kresli se do teto  bitmapy a ne rovnou do pictureboxu, kvuli blikani obrazu
            Graphics platno = Graphics.FromImage(bitmapaTemp), platno2 = pictureBoxOrientaceVoziku.CreateGraphics();

            if (checkBoxAntiAliasing.Checked == true)
                platno.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;  //antialiasing

            Rectangle rect = new Rectangle(110, 110, 36, 36);
            Point[] FLtriagle = { new Point(110, 110), new Point(110 - 44, 0), new Point(1, 1), new Point(0, 110 - 44) };
            Point[] FRtriagle = { new Point(110 + 36, 110), new Point(255, 110 - 44), new Point(254, 1), new Point(110 + 36 + 44, 0) };
            Point[] RLtriagle = { new Point(110, 110 + 36), new Point(110 - 44, 255), new Point(1, 254), new Point(0, 110 + 36 + 44) };
            Point[] RRtriagle = { new Point(110 + 36, 110 + 36), new Point(255, 110 + 36 + 44), new Point(254, 254), new Point(110 + 36 + 44, 255) };

            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();  //transformacni matice

            matrix.RotateAt((float)((float)((Uhel / 1000.0) * (180 / Math.PI))), new PointF(128, 128));       //rotace voziku
            matrix.Scale((float)(1 / Math.Sqrt(2)), (float)(1 / Math.Sqrt(2)), System.Drawing.Drawing2D.MatrixOrder.Append);                 //zmenseni o odm. ze 2, aby se veslo do pictureboxu
            matrix.Translate((float)(pictureBoxOrientaceVoziku.Width * (1 - (1 / Math.Sqrt(2))) / 2.0), (float)(pictureBoxOrientaceVoziku.Height * (1 - (1 / Math.Sqrt(2))) / 2.0), System.Drawing.Drawing2D.MatrixOrder.Append);    //posunuti na stred 

            platno.Clear(this.BackColor);             //vymazani
            platno.FillEllipse(new SolidBrush(Color.White), 0, 0, pictureBoxOrientaceVoziku.Width, pictureBoxOrientaceVoziku.Height);       //vnejsi kruznice

            platno.Transform = matrix;
            platno.FillRectangle(new SolidBrush(Color.Black), rect);
            platno.DrawLine(new Pen(Color.Crimson, 2), new Point(110 + 36 / 2, 110 + 35), new Point(110 + 36 / 2, 111));  //sipka urcujici smer voziku
            platno.DrawLine(new Pen(Color.Crimson, 2), new Point(111, 110 + 10), new Point(110 + 36 / 2, 111));
            platno.DrawLine(new Pen(Color.Crimson, 2), new Point(110 + 35, 110 + 10), new Point(110 + 36 / 2, 111));

            platno.FillClosedCurve(new SolidBrush(barvaFL), FLtriagle);
            platno.FillClosedCurve(new SolidBrush(barvaFR), FRtriagle);
            platno.FillClosedCurve(new SolidBrush(barvaRR), RRtriagle);
            platno.FillClosedCurve(new SolidBrush(barvaRL), RLtriagle);

            platno2.DrawImage(bitmapaTemp, 0, 0);

            if (barvaFL == Color.Red || barvaFR == Color.Red || barvaRL == Color.Red || barvaRR == Color.Red)  //pokud je detekovan predmet blize nez kriticka vzdalenost, pipne
                Console.Beep(800, 20);
        }

        private void pictureBoxOrientaceVoziku_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBoxOrientaceVoziku_Paint_1(object sender, PaintEventArgs e)
        {
            Graphics platno = e.Graphics;
    
            platno.Clear(this.BackColor);
            platno.FillEllipse(new SolidBrush(Color.White), 0, 0, pictureBoxOrientaceVoziku.Width, pictureBoxOrientaceVoziku.Height);       //vnejsi kruznice
        }

        private bool JoystickXUvnitrThreshold(int X)     //zjisti, zda je osa X joysticku uvnitr pasma necitlivosti
        {
            int threshold = (int)((ROZSAH_JOYSTICKU / 2) * (Convert.ToInt32(textBoxThreasholdPerc.Text) / 100.0));

            if ((ROZSAH_JOYSTICKU / 2 - threshold) > X || (ROZSAH_JOYSTICKU / 2 + threshold) < X)
                return false;

            return true;
        }

        private bool JoystickYUvnitrThreshold(int Y)     //zjisti, zda je osa Y joysticku uvnitr pasma necitlivosti
        {
            int threshold = (int)((ROZSAH_JOYSTICKU / 2) * (Convert.ToInt32(textBoxThreasholdPerc.Text) / 100.0));
            if ((ROZSAH_JOYSTICKU / 2 - threshold) > Y || (ROZSAH_JOYSTICKU / 2 + threshold) < Y)
                return false;

            return true;
        }

        private void buttonJoysticPripojeniRefresh_Click(object sender, EventArgs e)
        {
            try     //otestovat pripojeni joysticku
            {
                joystick = new USB_Joystick(0, ROZSAH_JOYSTICKU, 0.2, this);

                joystick.PresetValues();
                joystick.GetData();
                VykresliPoziciJoysticku();

                timerJoystick.Start();

                buttonSTART.Enabled = true;
                buttonJoysticPripojeniRefresh.Visible = false;   //zneviditelni tlacitko, umoznujici znovupripojeni joysticku
          
            }
            catch (Exception)
            {
                MessageBox.Show("Nebylo možno inicializovat joystick", "Pozor!", MessageBoxButtons.OK);

                buttonSTART.Enabled = false;
                buttonJoysticPripojeniRefresh.Visible = true;   //zviditelni tlacitko, umoznujici znovupripojeni joysticku
            }
        }
    }
}
