using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für Arrivals.xaml
    /// </summary>
    public partial class Arrivals : MetroWindow
    {
        Dictionary<int, string> NamesList = new Dictionary<int, string>();
        int firmenCount = 0;
        int besucherCount = 0;
        bool arrivalClicked = false;
        //bool kl_EinweisungClicked = false;
        //string query = "";
        MySqlCommand query = new MySqlCommand();
        byte[] _signature = null;
        Window mainWindow = null;
        string selectedID = "-1";
        int isBesucher = 0;
        string Name = "";
        int belegteParkplaetze = 0;
        int fzgCount = 0;
        int beID = -1;

        int kennzeichenHeight = 28;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="main"></param>
        /// <param name="id"></param>
        /// <param name="IsBesucher">0: Firma, 1: Besucher, 2: Family</param>
        public Arrivals(Window main, int id = -1, int IsBesucher = 0, string name = "")
        {
            InitializeComponent();
            arrivalClicked = false;

            mainWindow = main;

            selectedID = id == -1 ? name : id.ToString();
            isBesucher = IsBesucher;
            Name = name;

#if !DEBUG
            this.Topmost = true;
#endif


            if(isBesucher == 1)
            {
                TextBoxHelper.SetWatermark(tbVerantwortlPerson, "Name des Besuchers");
                TextBoxHelper.SetWatermark(tbNrVerantwortlPerson, "Telefonnummer des Besuchers");

                btnSignature.Visibility = Visibility.Collapsed;
            }

            //var park  = SQL.ReadListString($"SELECT parkplatznr FROM {MainWindow.table}.`parkplaetze`").Result;
            //var parkG = park.Where(p => p.StartsWith("G"));
            //var parkF = park.Where(p => !p.StartsWith("G"));

            //if (isBesucher == 1)
            //{
            //    var rectsG = BesuchP.Children.OfType<Rectangle>();

            //    foreach (Rectangle s in rectsG)
            //    {
            //        if (parkG.Contains(s.Name))
            //        {
            //            //var x = Helper.FindVisualChildren<Rectangle>(BE, s.Name).First();
            //            s.Fill = new SolidColorBrush(Colors.Red);
            //        }
            //        else if (!s.Name.StartsWith("Red"))
            //        {
            //            s.Fill = new SolidColorBrush(Colors.Green);
            //        }
            //    }
            //}


            tbAnzahlFzg.TextChanged += tbAnzahlFzg_TextChanged;
        }

        private async Task initialize()
        {
            var screen = WpfScreenHelper.Screen.FromHandle(new WindowInteropHelper(this).Handle);
            var workingArea = screen.WorkingArea;
            imgBE.MaxWidth = 1200;
            imgBE.Width = workingArea.Right - (this.Left + this.Width) - 40;

            var list = await SQL.ReadDictionary($"Select idFirmen, Name FROM {MainWindow.table}.firmen ORDER BY Name", 0, 1);
            //list = list.OrderBy(p => p.Value).ToDictionary();

            NamesList.Add(0, "Firmen:");
            NamesList.Add(999990, "------------");

            foreach (var keyValuePair in list)
                NamesList.Add(keyValuePair.Key, keyValuePair.Value);

            NamesList.Add(999991, "");
            NamesList.Add(999992, "============");
            NamesList.Add(999993, "");

            firmenCount = NamesList.Count;


            list = await SQL.ReadDictionary($"Select idBesucher, Name FROM {MainWindow.table}.besucher ORDER BY Name", 0, 1);
            //list.OrderBy(p => p).ToList();

            NamesList.Add(999994, "Besucher:");
            NamesList.Add(999995, "------------");

            foreach (var keyValuePair in list)
                NamesList.Add(Convert.ToInt32($"9999{keyValuePair.Key}"), keyValuePair.Value);


            NamesList.Add(999996, "");
            NamesList.Add(999997, "============");
            NamesList.Add(999998, "");

            besucherCount = NamesList.Count - firmenCount;


            list = await SQL.ReadDictionary($"Select idfamily, Name FROM {MainWindow.table}.family ORDER BY Name", 0, 1);
            //list.OrderBy(p => p).ToList();

            NamesList.Add(999999, "Führung:");
            NamesList.Add(1000000, "------------");


            foreach (var keyValuePair in list)
                NamesList.Add(Convert.ToInt32($"1111{keyValuePair.Key}"), keyValuePair.Value);



            await Dispatcher.BeginInvoke(new Action(async () =>
            {
                cbName.ItemsSource = NamesList;

                if (int.TryParse(selectedID, out int result) && selectedID != "-1")
                {
                    cbName.SelectionChanged += CbName_SelectionChanged;
                    //cbName.f = Parameter;
                    switch (isBesucher)
                    {
                        case 0:
                            cbName.SelectedValue = Convert.ToInt32(selectedID);
                            break;
                        case 1:
                            cbName.SelectedValue = Convert.ToInt32($"9999{selectedID}");
                            break;
                        case 2:
                            cbName.SelectedValue = Convert.ToInt32($"1111{selectedID}");
                            break;
                    }

                    //cbName.SelectedValue = isBesucher == 1 ? Convert.ToInt32($"9999{selectedID}") : Convert.ToInt32(selectedID);
                    tbAnzahlPersonen.Focus();

                    if (isBesucher == 0)
                    {
                        gridFirmenPark.Visibility = Visibility.Visible;
                        List<string> source = new List<string>();

                        bool exists = await SQL.RowExists(MainWindow.table + ".firmenPeople", "idFirmen", selectedID.ToString());

                        if (exists)
                        {
                            source = SQL.ReadListStringTwoColumns($"SELECT Personen, TelNr FROM {MainWindow.table}.firmenPeople WHERE idFirmen = '{selectedID}'", "|").Result.First().Split('|').ToList();
                            source = source.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
                        }

                        if (exists && source.Count > 1)
                        {                           
                            source[0] = source[0] + ";";
                            source[1] = source[1] + ";";

                            var res = SQL.ReadListStringMultipleColumns($"SELECT Verantwortlicher_MA_Firma,Tel_Nr_Verantwortlicher_Firma,Anzahl_Begleiter FROM {MainWindow.table}.firmen WHERE `idFirmen` = '{selectedID}' LIMIT 1").Result.First().Split(';');

                            if (!source[0].Contains(res[0]))
                            {
                                source[0] += res[0]; 
                                source[1] += res[1];
                            }

                            tbVerantwortlPerson.ItemsSource = source[0].TrimEnd(';').Split(';');
                            tbNrVerantwortlPerson.ItemsSource = source[1].TrimEnd(';').Split(';');

                            tbVerantwortlPerson.SelectedValue = res[0];
                            tbNrVerantwortlPerson.Text = res[1];
                            tbAnzahlPersonen.Text = Regex.IsMatch(res[2].ToString(), "[0-9]") ? (Convert.ToInt16(res[2]) + 1).ToString() : "";


                            if ((tbVerantwortlPerson.ItemsSource as string[]).Count() > 1)
                            {
                                tbMultiplePeople.Visibility = Visibility.Visible;

                                var tt = new ToolTip();
                                tt.Content = "Mehrere Personen stehen zur Auswahl";
                                tt.PlacementTarget = tbMultiplePeople;
                                tt.Placement = System.Windows.Controls.Primitives.PlacementMode.Right;
                                tt.HorizontalOffset = -20;
                                tt.VerticalOffset = 30;
                                tbMultiplePeople.ToolTip = tt;
                                tt.IsOpen = true;

                                System.Windows.Threading.DispatcherTimer t = new System.Windows.Threading.DispatcherTimer();
                                t.Interval = TimeSpan.FromSeconds(5);
                                t.Tick += (s, e) => { Dispatcher.Invoke(() => tt.IsOpen = false); t.Stop(); };
                                t.Start();
                            }
                        }
                        else
                        {
                            var res = SQL.ReadListStringMultipleColumns($"SELECT Verantwortlicher_MA_Firma,Tel_Nr_Verantwortlicher_Firma,Anzahl_Begleiter FROM {MainWindow.table}.firmen WHERE `idFirmen` = '{selectedID}' LIMIT 1").Result.First().Split(';');

                            tbVerantwortlPerson.ItemsSource = new List<string>() { res[0] };
                            tbNrVerantwortlPerson.ItemsSource = new List<string>() { res[1] };

                            tbVerantwortlPerson.SelectedValue = res[0];
                            tbNrVerantwortlPerson.SelectedValue = res[1];
                            tbAnzahlPersonen.Text = Regex.IsMatch(res[2].ToString(), "[0-9]") ? (Convert.ToInt16(res[2]) + 1).ToString() : "";
                        }
                    }
                    else if (isBesucher == 1)
                    {
                        var res = SQL.ReadListStringMultipleColumns($"SELECT Name,Tel_Nr_Besucher,Anzahl_Begleitpersonen FROM {MainWindow.table}.besucher WHERE `idbesucher` = '{selectedID}' LIMIT 1").Result.First().Split(';');

                        tbVerantwortlPerson.ItemsSource = new List<string>() { res[0] };
                        tbNrVerantwortlPerson.ItemsSource = new List<string>() { res[1] };

                        tbVerantwortlPerson.Text = res[0];
                        tbNrVerantwortlPerson.Text = res[1];
                        tbAnzahlPersonen.Text = (Convert.ToInt16(res[2]) + 1).ToString();

                    }
                    else if (isBesucher == 2)
                    {
                        var res = SQL.ReadListStringTwoColumns($"SELECT TelNr AS Tel_Nr_Besucher,AnzBegleiter FROM {MainWindow.table}.family WHERE `Name` = '{Name}' AND `Date` = '{DateTime.Now.Date.ToString("yyyy-MM-dd")}' LIMIT 1").Result.First().Split(';');

                        tbVerantwortlPerson.ItemsSource = new List<string>() { Name };
                        tbNrVerantwortlPerson.ItemsSource = new List<string>() { res[0] };

                        tbVerantwortlPerson.Text = Name;

                        tbNrVerantwortlPerson.Text = res[0];
                        tbAnzahlPersonen.Text = res[1];
                    }
                }
                else
                {
                    cbName.SelectionChanged += CbName_SelectionChanged;
                    cbName.IsDropDownOpen = true;
                }

                if (signoPad._stPad.DeviceGetCount() <= 0)
                {
                    btnSignature.IsEnabled = false;
                    btnCheck.IsEnabled = true;

                    btnSignature.ToolTip = "Kein Unterschriftenpad gefunden";
                }

            }));

            if (isBesucher == 0)
            {
                foreach (TextBlock tb in Helper.FindVisualChildren<TextBlock>(gridFirmenPark))//.Where(p => p.Tag == null))
                {
                    if (Regex.IsMatch(tb.Text, @"\d+"))
                    {
                        StackPanel sp = new StackPanel();

                        string parkplatz = tb.Text.PadLeft(2, '0');
                        var img = new BitmapImage(new Uri(@"pack://application:,,,/"
                                                        + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                                        + ";component/"
                                                        + $"Assets/Parkplatz/{parkplatz}.png", UriKind.Absolute));

                        sp.Children.Add(new TextBlock() { Text = $"Parkplatz {tb.Text.PadLeft(2, '0')}", FontWeight = FontWeights.Bold });
                        sp.Children.Add(new Image() { Source = img, Width = img.Width, Height = img.Height });

                        tb.ToolTip = sp;
                        ToolTipService.SetInitialShowDelay(tb, 100);
                        ToolTipService.SetBetweenShowDelay(tb, 100);
                    }
                }


                string x = SQL.ReadSingleValue($"SELECT BEint FROM {MainWindow.table}.firmen WHERE idFirmen = '{selectedID}'");
                string y = SQL.ReadSingleValue($"SELECT Parkplatz FROM {MainWindow.table}.beParkplaetze WHERE beNr = '{x}'").TrimEnd(',');

                beID = Convert.ToInt16(x != "" ? x : "-1");

                if (beID != -1)
                {
                    var be = Helper.GetBEFileNames(beID.ToString());
                    imgBE.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                                                    + ";component/"
                                                                    + $"{be}", UriKind.Absolute));
                    imgBE.Stretch = Stretch.UniformToFill;
                    lblParkNumbers.Text = $"Nur folgende Parkplätze vergeben: {y}";
                    popBE.IsOpen = true;
                }
            }

            if (isBesucher == 1)
            {
                gridBesucherPark.Visibility = Visibility.Visible;
                //GParkRow.Height = new GridLength(1.8, GridUnitType.Star);
                //this.Height = this.Height + 100;
                //GParkTop.Height = new GridLength(GParkTop.Height.Value + 100, GridUnitType.Pixel);

                var besucher = SQL.ReadSingleValue($"SELECT besucherList FROM {MainWindow.table}.besucherGroups WHERE idBesucher = '{selectedID}'");

                if (besucher.Contains(';'))
                {
                    var finalBesucher = besucher.TrimEnd(';').Split(';');
                    lblAngemeldeteBesucher.Text = $"{finalBesucher.Length} angemeldet";

                    foreach (var b in finalBesucher)
                    {
                        var lbl = new TextBlock() { Text = "- " + b, Height = 25, FontSize = 14 };
                        lbl.SetResourceReference(Control.ForegroundProperty, SystemColors.ControlTextBrushKey);

                        spBesucher.Children.Add(lbl);
                    }

                    popBesucher.Height = 50 + (finalBesucher.Length * 25) + 10;
                    popBesucher.IsOpen = true;
                }
            }

            usePark(await Task.Run(() => getPark()));
            checkPark();

            this.SizeChanged += MainWindow_SizeChanged;
        }

        private async Task<Tuple<List<string>, List<string>>> getPark()
        {
            //if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner)
            //{

            var park = await SQL.ReadListString($"SELECT Parkplatz FROM {MainWindow.table}.`beParkplaetze` LEFT JOIN {MainWindow.table}.`beBelegung` ON beParkplaetze.beNr = beBelegung.beNr WHERE Parkplatz IS NOT null AND CURDATE() BETWEEN beBelegung.von AND beBelegung.bis");
            var singlePark = await SQL.ReadDictionary2($"SELECT p.parkplatznr, f.Name FROM {MainWindow.table}.parkplaetze p LEFT JOIN {MainWindow.table}.firmen f ON f.idFirmen = p.firma", 0, 1);


            string list = "";

            list = string.Join("", park);

            park = list.Split(',').ToList();
            park = park.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();

            for (var p = 0; p < park.Count; p++) park[p] = park[p].PadLeft(2, '0');

            var justPark = park.ToList();

            park.AddRange(singlePark.Keys);

            return new Tuple<List<string>, List<string>> (justPark, park);
        }

        private void usePark(Tuple<List<string>, List<string>> parkLists)
        {
            var justPark = parkLists.Item1;
            var park = parkLists.Item2;

            var rects = gridFirmenPark.Children.OfType<Rectangle>();

            foreach (Rectangle s in rects)
            {
                if (park.Contains(s.Name.TrimStart('P').PadLeft(2, '0')))
                {
                    //var x = Helper.FindVisualChildren<Rectangle>(BE, s.Name).First();
                    s.Fill = new SolidColorBrush(Colors.Red);
                }
                else if (!s.Name.StartsWith("Red"))
                {
                    s.Fill = new SolidColorBrush(Colors.Green);
                }

            }

            if (BesuchP.Children.OfType<Grid>().Count() > 0)
            {
                var rectsG = BesuchP.Children.OfType<Grid>().First().Children.OfType<Rectangle>();

                foreach (Rectangle s in rectsG)
                {
                    if (park.Contains(s.Name))
                    {
                        //var x = Helper.FindVisualChildren<Rectangle>(BE, s.Name).First();
                        s.Fill = new SolidColorBrush(Colors.Red);
                    }
                    else if (!s.Name.StartsWith("Red"))
                    {
                        s.Fill = new SolidColorBrush(Colors.Green);
                    }

                }
            }

            if (isBesucher == 0)
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict = SQL.ReadDictionary2($"SELECT beNr, Parkplatz FROM {MainWindow.table}.beParkplaetze", 0, 1).Result;

                foreach (Rectangle rect in Helper.FindVisualChildren<Rectangle>(gridFirmenPark).Where(p => p.Fill.ToString() == Brushes.Red.ToString()))
                {
                    StackPanel sp = new StackPanel();

                    var nr = rect.Name.TrimStart('P').PadLeft(2, '0');

                    if (justPark.Contains(nr))
                    {
                        //var be = SQL.ReadSingleValue($"SELECT beNr FROM {MainWindow.table}.beParkplaetze WHERE Parkplatz LIKE '%{nr},%'");
                        var x = dict.Where(kv => kv.Value.Contains(nr)).Select(kv => kv.Key);
                        var be = x.Count() > 0 ? x.First() : "";
                        //Helper.FindVisualChildren<TextBlock>(BE, nr).First();

                        if (!string.IsNullOrWhiteSpace(be))
                        {
                            var img = new BitmapImage(new Uri(@"pack://application:,,,/"
                                                            + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                                            + ";component/"
                                                            + $"{Helper.GetBEFileNames(Convert.ToInt16(be))}", UriKind.Absolute));

                            sp.Children.Add(new TextBlock() { Text = $"{Helper.GetBEDescription(Convert.ToInt16(be))}", FontWeight = FontWeights.Bold });
                            sp.Children.Add(new Image() { Source = img, Width = img.Width / 1.5, Height = img.Height / 1.5 });

                            //rect.ToolTip = sp;
                            var tb = gridFirmenPark.FindChildren<TextBlock>().Where(p => p.Text == nr.TrimStart('0')).First();
                            tb.ToolTip = sp;
                            tb.PreviewMouseLeftButtonDown -= ParkSetPreviewMouseLeftButtonDown;

                            rect.Fill = new SolidColorBrush(Colors.Orange);
                        }
                    }
                }
            }


            belegteParkplaetze = rects.Where(p => p.Fill.ToString() == Brushes.Red.ToString()).Count();
        }

        private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var screen = WpfScreenHelper.Screen.FromHandle(new WindowInteropHelper(this).Handle);
            var workingArea = screen.WorkingArea;

            // Maximale Top-Position, sodass das Fenster unten nicht rausgeht
            if (this.Top + this.ActualHeight > workingArea.Bottom)
            {
                this.Top = workingArea.Bottom - this.ActualHeight;
            }

            // Optionale obere Begrenzung
            if (this.Top < workingArea.Top)
            {
                this.Top = workingArea.Top;
            }
        }

        private async void BtnCheck_Click(object sender, RoutedEventArgs e)
        {
            var zutritt = "";
            string kat = "1";
            
            var einweis = "";
            var kl_einweis = "";
            string asp = "";
            string anzFzg = "";
            int klUnterweis = 0;
            int anzFzgGemeldet = 0;

            DataTable table = new DataTable();

            if (cbName.SelectedIndex < firmenCount)
            {
                table = await SQL.ReadSQL($"Select * FROM {MainWindow.table}.firmen");
                kat = "1";
            }
            else if (cbName.SelectedIndex >= (firmenCount + besucherCount + 2))
            {
                table = await SQL.ReadSQL($"Select * FROM {MainWindow.table}.family");
                kat = "5";
            }
            else
            {
                table = await SQL.ReadSQL($"Select * FROM {MainWindow.table}.besucher");
                kat = "2";
            }

            foreach(DataRow row in table.Rows)
            {
                if (row.ItemArray[1].ToString() == cbName.SelectedItem.ToString().Split(',')[1].ToString().Replace("]", "").TrimStart(' ') || $"9999{row.ItemArray[0].ToString()}" == cbName.SelectedValue.ToString() || row.ItemArray[0].ToString() == cbName.SelectedValue.ToString())
                {
                    DateTime beginnDT;
                    DateTime endeDT;
                    DateTime einweisDT;
                    DateTime kl_einweisDT;


                    if (kat == "1")
                    {
                        if (string.IsNullOrWhiteSpace(tbAnzahlFzg.Text))
                        {
                            MessageBox.Show(this, "Anzahl Fahrzeuge eingeben", "Achtung!", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }

                        if (string.IsNullOrWhiteSpace(tbAnzahlPersonen.Text))
                        {
                            MessageBox.Show(this, "Anzahl Personen eingeben", "Achtung!", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }


                        if (DateTime.TryParse(row.ItemArray[7].ToString(), out beginnDT)
                            && DateTime.TryParse(row.ItemArray[8].ToString(), out endeDT))
                        {
                            if (DateTime.Now.Date >= beginnDT.Date && DateTime.Now.Date <= endeDT.Date)
                                zutritt = "OK";
                            else zutritt = "Prüfen!";
                        }
                        else
                        {
                            zutritt = $"Fehler! Bitte bei {row.ItemArray[10]} nachfragen";
                            einweis = $"Fehler! Bitte bei {row.ItemArray[10]} nachfragen";
                        }

                        if (Convert.ToInt16(tbAnzahlFzg.Text) <= Convert.ToInt16(row.ItemArray[5]))
                        {
                            anzFzg = "OK";
                        }
                        else
                        {
                            anzFzg = $"Nur {row.ItemArray[5].ToString()} Fahrzeug(e) angemeldet";
                        }

                        anzFzgGemeldet = row.ItemArray[5] != null ? Convert.ToInt16(row.ItemArray[5]) : 0;


                        if (DateTime.TryParse(row.ItemArray[9].ToString(), out einweisDT))
                        {
                            if(row.ItemArray[9].ToString() == "01.01.1903 00:00:00")
                            {
                                einweis = "Nur in Begleitung";
                            }
                            else if (DateTime.Now.Date <= einweisDT)
                                einweis = "OK";
                            else einweis = "Prüfen!";
                        }
                        else
                        {
                            zutritt = $"Fehler! Bitte bei {row.ItemArray[10]} nachfragen";
                            einweis = $"Fehler! Bitte bei {row.ItemArray[10]} nachfragen";
                        }

                        if(DateTime.TryParse(row.ItemArray[12].ToString(), out kl_einweisDT))
                        {
                            if (DateTime.Now.Date <= einweisDT)
                            {
                                kl_einweis = "OK";
                                klUnterweis = 1;
                            }
                            else
                            {
                                kl_einweis = "Kleine Unterweisung durchführen!";
                                klUnterweis = 0;
                            }
                        }
                        else
                        {
                            kl_einweis = "Bitte kleine Unterweisung durchführen!";
                            klUnterweis = 0;
                        }

                        asp = tbVerantwortlPerson.Text + " / " + tbNrVerantwortlPerson.Text; //row.ItemArray[10].ToString();
                    }

                    if (kat == "2")
                    {                      

                        if (DateTime.TryParse(row.ItemArray[5].ToString(), out beginnDT))
                        {
                            if (DateTime.Now.Date == beginnDT)
                                zutritt = "OK";
                            else zutritt = "Prüfen!";
                        }
                        else
                        {
                            zutritt = $"Fehler! Bitte bei {row.ItemArray[7]} nachfragen";
                            einweis = $"Fehler! Bitte bei {row.ItemArray[7]} nachfragen";
                        }


                        einweis = "--";
                        anzFzg = "--";

                        if (DateTime.TryParse(row.ItemArray[9].ToString(), out kl_einweisDT))
                        {
                            if (DateTime.Now.Date <= kl_einweisDT)
                            {
                                kl_einweis = "OK";
                                klUnterweis = 1;
                            }
                            else
                            {
                                kl_einweis = "Kleine Unterweisung durchführen!";
                                klUnterweis = 0;
                            }
                        }
                        else
                        {
                            kl_einweis = "Kleine Unterweisung durchführen!";
                            klUnterweis = 0;
                        }

                        asp = tbVerantwortlPerson.Text + " / " + tbNrVerantwortlPerson.Text;
                        //asp = row.ItemArray[7].ToString();
                    }

                    if(kat == "5")
                    {
                        zutritt = "OK";
                        anzFzg = "--";
                        kl_einweis = "--";
                        einweis = "--";
                        asp = tbVerantwortlPerson.Text + " / " + tbNrVerantwortlPerson.Text;
                    }
                }
            }

            lblAnmeldung.Content = zutritt;
            if (zutritt == "OK") lblAnmeldung.Background = new SolidColorBrush(Colors.LightGreen);
            else if (zutritt == "Prüfen!") lblAnmeldung.Background = new SolidColorBrush(Colors.LightYellow);
            else lblAnmeldung.Background = new SolidColorBrush(Colors.LightSalmon);

            lblFahrzeuge.Content = anzFzg;
            if (anzFzg == "OK") lblFahrzeuge.Background = new SolidColorBrush(Colors.LightGreen);
            else if (anzFzg.StartsWith("Nur")) lblFahrzeuge.Background = new SolidColorBrush(Colors.LightYellow);
            else if (anzFzg == "--") lblFahrzeuge.Background = new SolidColorBrush(Colors.LightGray);
            else lblFahrzeuge.Background = new SolidColorBrush(Colors.LightSalmon);


            lblEinweisung.Content = einweis;
            if (einweis == "OK") lblEinweisung.Background = new SolidColorBrush(Colors.LightGreen);
            else if (einweis == "Prüfen!") lblEinweisung.Background = new SolidColorBrush(Colors.LightYellow);
            else if (einweis == "--") lblEinweisung.Background = new SolidColorBrush(Colors.LightGray);
            else lblEinweisung.Background = new SolidColorBrush(Colors.LightSalmon);

            lblKleineUnterweisung.Content = kl_einweis;
            if (kl_einweis == "OK") lblKleineUnterweisung.Background = new SolidColorBrush(Colors.LightGreen);
            else if (kl_einweis == "Kleine Unterweisung durchführen!")
            {
                lblKleineUnterweisung.Background = new SolidColorBrush(Colors.LightYellow);
                lblKleineUnterweisung.Content = kl_einweis;
            }
            else lblKleineUnterweisung.Background = new SolidColorBrush(Colors.LightSalmon);


            var AnzPers = "0";
            var AnzFzg = "0";

            if (tbAnzahlFzg.Text != "")
                AnzFzg = tbAnzahlFzg.Text;

            if (tbAnzahlPersonen.Text != "")
                AnzPers = tbAnzahlPersonen.Text;

            if (einweis == "") einweis = "Fehlerhaft";
            if (zutritt == "") zutritt = "Fehlerhaft";

            arrivalClicked = true;
            btnClose_Copy.Visibility = Visibility.Collapsed;

            var kennzeichenTextboxes = spKennzeichen.Children.OfType<TextBox>().ToList();
            string kennzeichen = "";

            fzgCount = string.IsNullOrWhiteSpace(tbAnzahlFzg.Text) ? 0 : Convert.ToInt32(tbAnzahlFzg.Text);
            for (var i = 0; i < fzgCount; i++)
            {
                if (kennzeichenTextboxes.Count >= i)
                    if (kennzeichen == "")
                        kennzeichen = $"{((kennzeichenTextboxes[i]) as TextBox).Text}";
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(((kennzeichenTextboxes[i]) as TextBox).Text))
                            kennzeichen = $"{kennzeichen} / {((kennzeichenTextboxes[i]) as TextBox).Text}";
                    }
            }

            if (int.TryParse(selectedID, out int result))
            {
                var idFirma_Besucher = selectedID.StartsWith("9999") ? Convert.ToInt32(selectedID.ToString().Substring(3)) : Convert.ToInt32(selectedID);
                //query = $"INSERT INTO {MainWindow.table}.zutritte (Kategorie,Name,Zutritt,Pruefung_Zutritt,Pruefung_Einweisung,AnzahlPers,AnzahlFzg,Ansprechpartner,Kl_Unterweisung,Fzg_gemeldet,Kennzeichen,Bemerkung,signature_blob,idFirma_Besucher) VALUES ('{kat}','{cbName.Text.ToString().Replace(",", ";")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{zutritt}','{einweis}','{AnzPers.Replace(",", ";")}','{AnzFzg.Replace(",", ";")}','{asp.Replace(",", ";")}','{klUnterweis}','{anzFzgGemeldet}','{kennzeichen}','{tbBemerkung.Text}',@signature,'{idFirma_Besucher}')";
                //query = $"INSERT INTO {MainWindow.table}.zutritte (Kategorie,Name,Zutritt,Pruefung_Zutritt,Pruefung_Einweisung,AnzahlPers,AnzahlFzg,Ansprechpartner,Kl_Unterweisung,Fzg_gemeldet,Kennzeichen,Bemerkung,signature_blob,idFirma_Besucher) VALUES (@kat,@name,@time,@zutritt,@einweis,@anzPers,@anzFzg,@asp,@klUnterweis,@anzFzgGemeldet,@kennzeichen,@bemerkung,@idFirma_Besucher)";

                query = SQL.CreateAndReturnSQLCommand($"INSERT INTO {MainWindow.table}.zutritte (Kategorie,Name,Zutritt,Pruefung_Zutritt,Pruefung_Einweisung,AnzahlPers,AnzahlFzg,Ansprechpartner,Kl_Unterweisung,Fzg_gemeldet,Kennzeichen,Bemerkung,signature_blob,idFirma_Besucher) VALUES (@kat,@name,@time,@zutritt,@einweis,@anzPers,@anzFzg,@asp,@klUnterweis,@anzFzgGemeldet,@kennzeichen,@bemerkung,@signature,@idFirma_Besucher)", new List<MySqlParameter>()
                {
                    new MySqlParameter("@kat",kat),
                    new MySqlParameter("@name", cbName.Text.ToString().Replace(",", ";")),
                    new MySqlParameter("@time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    new MySqlParameter("@zutritt", zutritt),
                    new MySqlParameter("@einweis", einweis),
                    new MySqlParameter("@anzPers", AnzPers.Replace(",", ";")),
                    new MySqlParameter("@anzFzg", AnzFzg.Replace(",", ";")),
                    new MySqlParameter("@asp", asp.Replace(",", ";")),
                    new MySqlParameter("@klUnterweis", klUnterweis),
                    new MySqlParameter("@anzFzgGemeldet", anzFzgGemeldet),
                    new MySqlParameter("@kennzeichen", kennzeichen),
                    new MySqlParameter("@bemerkung", tbBemerkung.Text),
                    new MySqlParameter("@idFirma_Besucher", idFirma_Besucher)
                });

                btnSignature.IsEnabled = true;
            }
            else
            {
                //query = $"INSERT INTO {MainWindow.table}.zutritte (Kategorie,Name,Zutritt,Pruefung_Zutritt,Pruefung_Einweisung,AnzahlPers,AnzahlFzg,Ansprechpartner,Kl_Unterweisung,Fzg_gemeldet,Kennzeichen,Bemerkung) VALUES ('{kat}','{cbName.Text.ToString().Replace(",", ";")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{zutritt}','{einweis}','{AnzPers.Replace(",", ";")}','{AnzFzg.Replace(",", ";")}','{asp.Replace(",", ";")}','{klUnterweis}','{anzFzgGemeldet}','{kennzeichen}','{tbBemerkung.Text}')";


                query = SQL.CreateAndReturnSQLCommand($"INSERT INTO {MainWindow.table}.zutritte (Kategorie,Name,Zutritt,Pruefung_Zutritt,Pruefung_Einweisung,AnzahlPers,AnzahlFzg,Ansprechpartner,Kl_Unterweisung,Fzg_gemeldet,Kennzeichen,Bemerkung) VALUES (@kat,@name,@time,@zutritt,@einweis,@anzPers,@anzFzg,@asp,@klUnterweis,@anzFzgGemeldet,@kennzeichen,@bemerkung)", new List<MySqlParameter>()
                {
                    new MySqlParameter("@kat",kat),
                    new MySqlParameter("@name", cbName.Text.ToString().Replace(",", ";")),
                    new MySqlParameter("@time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    new MySqlParameter("@zutritt", zutritt),
                    new MySqlParameter("@einweis", einweis),
                    new MySqlParameter("@anzPers", AnzPers.Replace(",", ";")),
                    new MySqlParameter("@anzFzg", AnzFzg.Replace(",", ";")),
                    new MySqlParameter("@asp", asp.Replace(",", ";")),
                    new MySqlParameter("@klUnterweis", klUnterweis),
                    new MySqlParameter("@anzFzgGemeldet", anzFzgGemeldet),
                    new MySqlParameter("@kennzeichen", kennzeichen),
                    new MySqlParameter("@bemerkung", tbBemerkung.Text),
                });

                btnSignature.IsEnabled = false;
            }


            if (klUnterweis == 0) btnKlEinweisung_durchgeführt.IsEnabled = true;
            else if (klUnterweis == 1)
            {
                btnKlEinweisung_durchgeführt.ToolTip = "Kleine Unterweisung wurde bereits durchgeführt\nBestätigung nicht nötig";
                btnSignature.ToolTip = "Kleine Unterweisung wurde bereits durchgeführt\nUnterschrift nicht nötig";
                btnSignature.Content = "Unterschrift bereits vorhanden";
            }

            if (arrivalClicked)
            {
                btnKarte.IsEnabled = true;

                if (SQL.ReadSingleValue($"SELECT EXISTS (SELECT * FROM {MainWindow.table}.karten WHERE benutzer = '{tbVerantwortlPerson.Text}' AND farbe = 'Grün')") == "1")
                {
                    btnKarte.Content = $"{tbVerantwortlPerson.Text} hat bereits eine grüne Karte\nZusätzliche Personen können hier eingetragen werden";
                    btnClose.IsEnabled = true;
                }
            }


            if (kat == "2")
            {
#if !DEBUG
                // Vorerst deaktiviert, da ich beim Pförtner überprüfen muss ob das alles so funktioniert
                //
                //
                //if (MainWindow.LoggedInRole == Roles.Pförtner)
                //{
                //    Helper.PrintPDF("\\\\mhb00swfs003v.fv-werke.db.de\\GLW99\\ZKuP\\Einweisungsflyer.pdf");
                //    btnCheck.Content = "Einweisungflyer wird gedruckt...";
                //}
#endif
            }
        }

        private void checkPark()
        {
            var rects = gridFirmenPark.Children.OfType<Rectangle>();

            if (int.TryParse(tbAnzahlFzg.Text, out int anz))
                if (anz > 0 && beID == -1)
                    if ((rects.Where(p => p.Fill.ToString() == Brushes.Red.ToString()).Count() - belegteParkplaetze) >= anz)
                    {
                        lblSelectAParkplatz.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        lblSelectAParkplatz.Visibility = Visibility.Visible;
                    }
                else if (anz > 0 && beID != -1)
                    lblSelectAParkplatz.Visibility = Visibility.Collapsed;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            try
            {
                if (arrivalClicked)
                {
                    e.Cancel = true;
                    MessageBox.Show(this, "Ankunft wurde geklickt\n\nBitte Fenster über \"Schließen\"-Button schließen", "Fehler", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                signoPad.CloseConnection();
                mainWindow.Focus();
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.ToString());
                
                MessageBox.Show("Fehler: " + ex.Message);
            }
        }



        private async void Close_Click(object sender, RoutedEventArgs e)
        {
            if (arrivalClicked)
            {
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.changes SET timestamp = @time WHERE `table` = 'arrivals'", new List<MySqlParameter>()
                {
                    new MySqlParameter("@time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                });

                try
                {
                    if (_signature != null)
                    {
                        await SQL.CreateAndWriteSQLwithSignature(query, _signature);
                    }
                    else
                    {
                        query.CommandText = query.CommandText.Replace(",@signature", "");
                        query.CommandText = query.CommandText.Replace(",signature_blob", "");

                        await SQL.CreateAndWriteSQL(query);
                    }

                    arrivalClicked = false;

                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Bei der Übertragung der Daten ist ein Fehler aufgetreten.\nBitte die Ankunft nochmal bestätigen.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    Log.WriteLog(ex.ToString());

                    this.Close();
                }                
            }

            signoPad.CloseConnection();
            signoPad.CloseConnection();
        }

        private async void CbName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbName.SelectedItem != null)
            {
                if(cbName.SelectedItem.ToString() == "------------" || cbName.SelectedItem.ToString() == "============" || cbName.SelectedItem.ToString() == "Besucher:" || cbName.SelectedItem.ToString() == "Firmen:" || (cbName.SelectedItem.ToString() == "" && cbName.SelectedIndex != -1))
                {
                    cbName.SelectedIndex = -1;
                    MessageBox.Show(this, "Dieses Feld kann nicht gewählt werden", "Fehler!", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                string a_Fzg = "0";
                if (cbName.SelectedIndex < firmenCount)
                {
                    a_Fzg = await SQL.ReadSingleValueAsync($"SELECT Anzahl_Fzg FROM {MainWindow.table}.firmen WHERE `idFirmen`='{selectedID}' AND `Arbeitsbeginn` <= current_date() AND `Arbeitsende` >= current_date()");
                    lblAngemeldeteFzg.Text = !string.IsNullOrWhiteSpace(a_Fzg) ? a_Fzg + " Fzg. angemeldet" : "keine Fzg. angemeldet";
                    tbAnzahlFzg.Text = !string.IsNullOrWhiteSpace(a_Fzg) ? a_Fzg : "";
                }
                else
                {
                    lblAngemeldeteFzg.Text = "Besucher nur ohne Fzg.";
                    tbAnzahlFzg.Text = "0";
                }

                //spKennzeichen.Children.Clear();
                
                //if (!string.IsNullOrWhiteSpace(a_Fzg))
                //{
                //    fzgCount = Convert.ToInt16(a_Fzg);

                //    for (var i = 0; i < fzgCount; ++i)
                //    {
                //        spKennzeichen.Children.Add(new TextBox()
                //        {
                //            Name = $"tbKennzeichen{i + 1}",
                //            Height = 23,
                //            Margin = new Thickness(0, 2, 0, 0),
                //            TextWrapping = TextWrapping.Wrap,
                //            VerticalAlignment = VerticalAlignment.Top,
                //            TextAlignment = TextAlignment.Center,
                //            Padding = new Thickness(0, 2, 0, 0),
                //            TabIndex = 5 + i
                //        });

                //        spKennzeichen.Children.Add(new TextBlock()
                //        {
                //            Margin = new Thickness(0, -21, 0, 0),
                //            Width = 100,
                //            TextWrapping = TextWrapping.Wrap,
                //            Text = $"{i+1}. Kennzeichen",
                //            VerticalAlignment = VerticalAlignment.Top,
                //            HorizontalAlignment = HorizontalAlignment.Left,
                //            Foreground = new SolidColorBrush(Colors.Gray),
                //            Padding = new Thickness(5, 0, 0, 0)
                //        });

                //        this.Height = this.Height + kennzeichenHeight;
                //    }
                //}

                btnCheck.IsEnabled = true;
                btnKarte.IsEnabled = true;
            }            
        }




        List<string> selectedPark = new List<string>();
        string time = "";
        private async void ParkSetPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (MainWindow.LoggedInRole == Roles.Pförtner || MainWindow.LoggedInRole == Roles.Admin)
            {
                if (time == "") time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var parkplatz = (sender as TextBlock).Text;

                if ((parkplatz == "7" && gridFirmenPark.Children.OfType<Rectangle>().Where(p => p.Name == $"P7").First().Fill.ToString() == Colors.Green.ToString()))
                    MessageBox.Show("Dieser Parkplatz darf nur an DB Energie vergeben werden!", "DB Energie Parkplatz", MessageBoxButton.OK, MessageBoxImage.Information);
                if ((parkplatz == "34" && gridFirmenPark.Children.OfType<Rectangle>().Where(p => p.Name == $"P34").First().Fill.ToString() == Colors.Green.ToString()))
                    MessageBox.Show("Dieser Parkplatz darf nur an DB Energie vergeben werden!", "DB Energie Parkplatz", MessageBoxButton.OK, MessageBoxImage.Information);

                if (parkplatz == "6" && gridFirmenPark.Children.OfType<Rectangle>().Where(p => p.Name == $"P6").First().Fill.ToString() == Colors.Green.ToString())
                    MessageBox.Show("Dieser Parkplatz darf nur an DB InfraGO vergeben werden!", "DB InfraGO Parkplatz", MessageBoxButton.OK, MessageBoxImage.Information);




                foreach (var rect in gridFirmenPark.Children.OfType<Rectangle>())
                {
                    if (rect.Name == "P" + parkplatz)
                    {
                        if (rect.Fill.ToString() == Colors.Red.ToString())
                        {
                            rect.Fill = new SolidColorBrush(Colors.Green);
                            //await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.parkplaetze WHERE parkplatznr={parkplatz}");
                            var command = new MySqlCommand($"DELETE FROM {MainWindow.table}.parkplaetze WHERE parkplatznr = @pParkplatz");
                            command.Parameters.Add(new MySqlParameter("pParkplatz", parkplatz));
                            await SQL.WriteSQL(command);
                            selectedPark.Remove(parkplatz);
                        }
                        else if (rect.Fill.ToString() == Colors.Green.ToString())
                        {
                            rect.Fill = new SolidColorBrush(Colors.Red);
                            //await SQL.WriteSQL($"INSERT INTO {MainWindow.table}.parkplaetze (parkplatznr) VALUES ({parkplatz})");
                            var command = new MySqlCommand($"INSERT INTO {MainWindow.table}.parkplaetze (parkplatznr, firma, AusgegebenDurch, AusgegebenTimestamp, TelVerantwortlicherFirma) VALUES (@pParkplatz, @pFirma, @pAusgeber, @pTime, @pTel)");
                            
                            command.Parameters.Add(new MySqlParameter("pParkplatz", parkplatz));
                            command.Parameters.Add(new MySqlParameter("pFirma", cbName.SelectedValue.ToString()));
                            command.Parameters.Add(new MySqlParameter("pAusgeber", Helper.InsertSpaceBeforeUpperCase(Environment.UserName)));
                            command.Parameters.Add(new MySqlParameter("pTime", time));
                            command.Parameters.Add(new MySqlParameter("pTel", tbNrVerantwortlPerson.Text));


                            await SQL.WriteSQL(command);
                            selectedPark.Add(parkplatz);
                        }
                    }
                }


                if (selectedPark.Count > 0)
                {
                    string s = "";
                    s = String.Join(", ", selectedPark.OrderBy(p => p));
                    //s = s.TrimEnd(',');
                    borderParkkarteFirmaAusgeben.Visibility = Visibility.Visible;
                    lblParkkarteFirmaAusgeben.Text = $"Parkkarte Nr. {s}\nan Firma   {cbName.Text}   ausgeben";
                }
                else
                {
                    lblParkkarteFirmaAusgeben.Text = "";
                    borderParkkarteFirmaAusgeben.Visibility = Visibility.Collapsed;
                }

                checkPark();
            }
        }


        List<string> selectedGPark = new List<string>();
        private async void G_ParkPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var block = sender as TextBlock;
            var parkplatz = block.Text;

            foreach (var rect in BesuchP.Children.OfType<Rectangle>())
            {
                if (rect.Name == "G" + parkplatz)
                {
                    if (rect.Fill.ToString() == Colors.Red.ToString())
                    {
                        rect.Fill = new SolidColorBrush(Colors.Green);
                        await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.parkplaetze WHERE parkplatznr='G{parkplatz}'");
                        selectedGPark.Remove(parkplatz);
                    }
                    else if (rect.Fill.ToString() == Colors.Green.ToString())
                    {
                        rect.Fill = new SolidColorBrush(Colors.Red);
                        //await SQL.WriteSQL($"INSERT INTO {MainWindow.table}.parkplaetze (parkplatznr) VALUES ('G{parkplatz}')");
                        await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.parkplaetze (parkplatznr, AusgegebenDurch) VALUES (@parkplatznr, @ausgegeben)", new List<MySqlParameter>()
                        {
                            new MySqlParameter("@parkplatznr", $"G{parkplatz}"),
                            new MySqlParameter("@ausgegeben", Helper.InsertSpaceBeforeUpperCase(Environment.UserName))
                        });

                        selectedGPark.Add(parkplatz);
                    }
                }
            }

            if (selectedGPark.Count > 0)
            {
                string s = "";
                s = String.Join(", ", selectedGPark.OrderBy(p => p));
                //s = s.TrimEnd(',');
                borderParkkarteAusgeben.Visibility = Visibility.Visible;
                lblParkkarteAusgeben.Text = $"Parkkarte Nr. {s}\nan Besucher {cbName.Text} ausgeben";
            }
            else
            {
                lblParkkarteAusgeben.Text = "";
                borderParkkarteAusgeben.Visibility = Visibility.Collapsed;
            }
        }


        private async void btnSignature_Click(object sender, RoutedEventArgs e)
        {
            //string kat = "1";
            //string firmaBesucher = "";
            string name = "";

            var kennzeichenTextboxes = spKennzeichen.Children.OfType<TextBox>().ToList();
            string kennzeichen = "";

            if (kennzeichenTextboxes != null)
            {
                for (var i = 0; i < fzgCount; i++)
                {
                    if (kennzeichenTextboxes.Count >= i)
                        if (kennzeichen == "")
                            kennzeichen = $"{((kennzeichenTextboxes[i]) as TextBox).Text}";
                        else
                            kennzeichen = $"{kennzeichen} / {((kennzeichenTextboxes[i]) as TextBox).Text}";
                }
            }
            //if (cbName.SelectedIndex < firmenCount)
            //{
            //    //firmaBesucher = cbName.SelectedItem.ToString();
            //    name = await SQL.ReadSingleValueAsync($"SELECT Verantwortlicher_MA_Firma FROM {MainWindow.table}.firmen WHERE `idFirmen` = '{selectedID}'");
            //}
            //else
            //{
            //    //firmaBesucher = cbName.SelectedItem.ToString();
            //    name = await SQL.ReadSingleValueAsync($"SELECT Ansprechpartner_Intern FROM {MainWindow.table}.besucher WHERE `idBesucher` = '{selectedID}'");
            //}

            name = tbVerantwortlPerson.Text;

            Sign(name, kennzeichen);
        }

        private void Sign(string name, string kennzeichen)
        {
            if (signoPad._stPad.DeviceGetCount() > 0)
            {
                var sig = new Signature(Signature.DisclaimerType.Parken, name, cbName.SelectedItem.ToString(), kennzeichen);
                if (sig.ShowDialog() == false)
                {
                    if (sig.ResultByte != null)
                    {
                        _signature = sig.ResultByte;

                        btnCheck.IsEnabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Keine Unterschrift, erneut versuchen", "Keine Unterschrift", MessageBoxButton.OK, MessageBoxImage.Error);
                        Sign(name, kennzeichen);
                    }
                }
            }
            else
                MessageBox.Show("Kein Unterschriftenpad gefunden\nMeldung 0x01", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private async void btnKlEinweisung_durchgeführt_Click(object sender, RoutedEventArgs e)
        {
            if (signoPad._stPad.DeviceGetCount() <= 0)
            {
                btnSignature.IsEnabled = false;
                btnSignature.ToolTip = "Kein Unterschriftenpad gefunden";
            }
            else { btnSignature.IsEnabled = true; btnSignature.Content = "Unterschrift einholen!"; }

            if (!cbName.SelectedValue.ToString().StartsWith("9999"))
            {
                //await SQL.WriteSQL($"UPDATE {MainWindow.table}.firmen SET Kleine_Unterweisung_bis = '{(DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")}' WHERE `idFirmen` = '{selectedID}'");
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.firmen SET Kleine_Unterweisung_bis = @DateTime WHERE `idFirmen` = @selectedID", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@DateTime", (DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")),
                                                new MySqlParameter("@selectedID", selectedID)
                                            });
            }
            else
            {
                //await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Kleine_Unterweisung_bis = '{(DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")}' WHERE `idBesucher` = '{selectedID}'");
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.besucher SET Kleine_Unterweisung_bis = @DateTime WHERE `idBesucher` = @selectedID", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@DateTime", (DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")),
                                                new MySqlParameter("@selectedID", selectedID)
                                            });
            }

            //
            // Fehler s[20] beheben, Spalte 20 vermutlich falsch
            // Tritt nur mit Button kleine Einweisung aus
            //
            var qText = query.CommandText;
            var s = qText.Split(',');
            s[21] = "1";
            query.CommandText = string.Join(",", s);

            btnKlEinweisung_durchgeführt.Background = new SolidColorBrush(Colors.GreenYellow);
        }

        private void btnKarte_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbAnzahlPersonen.Text))
            {
                var ap = SQL.ReadSingleValue($"SELECT Ansprechpartner_Intern FROM {MainWindow.table}.firmen WHERE idFirmen='{selectedID}'");
                var user = "";
                if(isBesucher == 1 && Convert.ToInt16(tbAnzahlPersonen.Text) > 1)
                {
                    user = SQL.ReadSingleValue($"SELECT besucherList FROM {MainWindow.table}.besucherGroups WHERE idbesucher = '{selectedID}'");
                }

                for (var i = 0; i < Convert.ToInt16(tbAnzahlPersonen.Text); i++)
                {
                    if (i == 0)
                    {
                        var hasEinweisung = lblEinweisung.Background.ToString() == Brushes.LightGreen.ToString() ? true : false;

                        if (isBesucher == 1)
                        {
                            AddCardUser aI = new AddCardUser(tbVerantwortlPerson.Text, true, (i + 1).ToString() + " / " + tbAnzahlPersonen.Text, ap, true, hasEinweisung, "", tbNrVerantwortlPerson.Text);
                            aI.Owner = this;
                            aI.ShowDialog();
                        }
                        else
                        {
                            AddCardUser aI = new AddCardUser(tbVerantwortlPerson.Text, false, (i + 1).ToString() + " / " + tbAnzahlPersonen.Text, ap, true, hasEinweisung, cbName.Text, tbNrVerantwortlPerson.Text, selectedID);
                            aI.Owner = this;
                            aI.ShowDialog();
                        }

                    }
                    else
                    {
                        var hasEinweisung = lblEinweisung.Background.ToString() == Brushes.LightGreen.ToString() ? true : false;

                        var u = "";
                        if (user.Contains(';')) u = user.Split(';')[i - 1];

                        if (isBesucher == 1)
                        {
                            AddCardUser aI = new AddCardUser(u, true, (i + 1).ToString() + " / " + tbAnzahlPersonen.Text, ap, false, hasEinweisung, "");
                            aI.Owner = this;
                            aI.ShowDialog();
                        }
                        else
                        {
                            AddCardUser aI = new AddCardUser(u, false, (i + 1).ToString() + " / " + tbAnzahlPersonen.Text, ap, false, hasEinweisung, cbName.Text, "", selectedID);
                            aI.Owner = this;
                            aI.ShowDialog();
                        }
                    }
                }


                if (arrivalClicked) btnClose.IsEnabled = true;
            }
            else MessageBox.Show("Anzahl Personen muss angegeben werden", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void Window_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            this.Opacity = 1;
        }

        private void Window_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            this.Opacity = 0.5;
        }

        private void CloseWithX_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            await initialize();            

            spinnerCanvas.Visibility = Visibility.Collapsed;



            //tbAnzahlFzg.Text = "0";


            Helper.CheckWindowIsInScreenSpace(this);
        }

        private void tbAnzahlPersonen_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Regex.IsMatch(e.Text, "[0-9]"))
            {
                e.Handled = true;
                ToolTip tip = new ToolTip();
                tip.Content = "Nur Zahlen erlaubt";
                tip.StaysOpen = false;
                (sender as TextBox).ToolTip = tip;
                tip.IsOpen = true;
            }
        }

        private void tbAnzahlFzg_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Regex.IsMatch(e.Text, "[0-9]"))
            {
                e.Handled = true;
                ToolTip tip = new ToolTip();
                tip.Content = "Nur Zahlen erlaubt";
                tip.StaysOpen = false;
                (sender as TextBox).ToolTip = tip;
                tip.IsOpen = true;
            }
        }



        bool alreadyWarned = false;
        bool secondRun = false;
        private void tbAnzahlFzg_TextChanged(object sender, TextChangedEventArgs e)
        {
            var tb = (sender as TextBox).Text;
            if (isBesucher == 1 && tb != "0" && !string.IsNullOrWhiteSpace(tb) && !alreadyWarned)
            {
                MessageBox.Show("Besucher dürfen nicht mit einem Fahrzeug einfahren!\nDem Besucher einen Besucherparkplatz zuweisen!", "Einfahrt verboten!", MessageBoxButton.OK, MessageBoxImage.Error);
                alreadyWarned = true;
                //e.Handled = true;
            }

            if (Regex.IsMatch(tb, "^0.") || string.IsNullOrWhiteSpace(tb))
            {
                //this.Height = this.Height - (spKennzeichen.Children.Count / 2) * kennzeichenHeight;
                if (isBesucher == 0)
                { 
                    this.Height = this.MinHeight;

                    lblSelectAParkplatz.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                fzgCount = Convert.ToInt16(tb);
                spKennzeichen.Children.Clear();
                //spKennzeichen.Height = 0;
                if (isBesucher == 0)
                    this.Height = this.MinHeight;
                //else if (isBesucher == 1)
                //    this.Height = this.MinHeight + 100;

                for (var i = 0; i < fzgCount; ++i)
                {
                    spKennzeichen.Children.Add(new TextBox()
                    {
                        Name = $"tbKennzeichen{i + 1}",
                        Height = 23,
                        Margin = new Thickness(0, 2, 0, 0),
                        TextWrapping = TextWrapping.Wrap,
                        VerticalAlignment = VerticalAlignment.Top,
                        TextAlignment = TextAlignment.Center,
                        Padding = new Thickness(0, 2, 0, 0),
                        TabIndex = 5 + i
                    });

                    TextBoxHelper.SetWatermark((spKennzeichen.Children[spKennzeichen.Children.Count - 1] as TextBox), $"{i + 1}. Kennzeichen");

                    (spKennzeichen.Children[spKennzeichen.Children.Count - 1] as TextBox).CharacterCasing = CharacterCasing.Upper;
                    //spKennzeichen.Children.Add(new TextBlock()
                    //{
                    //    Margin = new Thickness(0, -21, 0, 0),
                    //    Width = 100,
                    //    TextWrapping = TextWrapping.Wrap,
                    //    Text = $"{i + 1}. Kennzeichen",
                    //    VerticalAlignment = VerticalAlignment.Top,
                    //    HorizontalAlignment = HorizontalAlignment.Left,
                    //    Foreground = new SolidColorBrush(Colors.Gray),
                    //    Padding = new Thickness(5, 0, 0, 0)
                    //});

                    //this.Height = this.Height + kennzeichenHeight;
                }

                this.Height = this.Height + (spKennzeichen.Children.Count) * kennzeichenHeight;
                spKennzeichen.Height = (spKennzeichen.Children.Count) * kennzeichenHeight;
                kennzeichenRow.Height = new GridLength(spKennzeichen.Height);
            }


            if(secondRun) checkPark();
            secondRun = true;
        }

        private void btnCloseBE_Click(object sender, RoutedEventArgs e)
        {
            popBE.IsOpen = false;
        }

        private void btnClosePopBesucher_Click(object sender, RoutedEventArgs e)
        {
            popBesucher.IsOpen = false;
        }



        private void Window_LocationChanged(object sender, EventArgs e)
        {
            Helper.CheckWindowIsInScreenSpace(this);
        }
    }
}
