using ColorHelper;
using ControlzEx.Standard;
using FuzzySharp;
using MahApps.Metro.Controls;
using Microsoft.Toolkit.Uwp.Notifications;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices.AccountManagement;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Windows.UI.Composition;
using Process = System.Diagnostics.Process;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            System.Diagnostics.Debug.WriteLine("PropertyChanged   " + propertyName);
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public const string Version = "5.1.0.4"; 
        public static Roles LoggedInRole { get; private set; } = Roles.None;


//#warning No Release, Tabellen vertauscht
#if DEBUG
        public static string table { get; } = "zkupTestEnv";//
#elif !DEBUG
        public static string table { get; } = "zkup";
#endif
        public string NoToolTip { get; } = "Doppelklick um Ankunft zu Bestätigen";

        private List<Overview> overview = new List<Overview>();
        public List<Overview> Overviews
        {
            get { return overview; }
            set { overview = value; OnPropertyChanged(); }
        }

        private DataTable parkEmailUsers = new DataTable("ParkEmailUsers");
        public DataTable ParkEmailUsers
        {
            get { return parkEmailUsers; }
            set { parkEmailUsers = value; OnPropertyChanged(); }
        }

        private DataTable fzgAnmeldungEmailUsers = new DataTable("FzgAnmeldungEmailUsers");
        public DataTable FzgAnmeldungEmailUsers
        {
            get { return fzgAnmeldungEmailUsers; }
            set { fzgAnmeldungEmailUsers = value; OnPropertyChanged(); }
        }



        DataTable overv = new DataTable("Overview");
        DataTable todayFirm = new DataTable("TodayFirm");
        DataTable todayBesuch = new DataTable("TodayBesuch");
        DataTable todayFamily = new DataTable("TodayFamily");
        

        DispatcherTimer reloadTimer = new DispatcherTimer();
        DispatcherTimer reloadTimerHinweis = new DispatcherTimer();
        DispatcherTimer checkUpdateTimer = new DispatcherTimer();
        DispatcherTimer connTimer = new DispatcherTimer();
        DispatcherTimer ausfahrtTimer = new DispatcherTimer();

        RoutedCommand resetWindow;
        //RoutedCommand skullWindow;

        int maxBikes = 24;
        bool ReadyToSavePosition = false;
        bool isSecureConn = false;

        public MainWindow()
        {
            InitializeComponent();

            Startup();
        }

        private async void Startup()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            await CheckConnection(true);

            cbShowParkcardToAccept.IsChecked = Settings.GetSettingBool("ShowParkcardAccept");

            lblVersion.Text = "Version " + Version;



            //if ((Settings.GetSettingDouble("Width") + Settings.GetSettingDouble("Left")) >= System.Windows.SystemParameters.PrimaryScreenWidth) CenterWindowOnScreen(this);
            //if ((Settings.GetSettingDouble("Height") + Settings.GetSettingDouble("Top")) >= System.Windows.SystemParameters.PrimaryScreenHeight) CenterWindowOnScreen(this);

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") || File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") != File.GetLastWriteTime(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe"))
            {
                File.Copy(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", true);
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png") || File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png") != File.GetLastWriteTime(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuP.png"))
            {
                File.Copy(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuP.png", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png", true);
            }

            CheckWorkingDir();
            CheckVersion();
            CheckMaintenance();
            CheckNotification();


            resetWindow = new RoutedCommand();
            resetWindow.InputGestures.Add(new KeyGesture(Key.R, ModifierKeys.Control));
            //skullWindow = new RoutedCommand();
            //skullWindow.InputGestures.Add(new KeyGesture(Key.P, ModifierKeys.Control | ModifierKeys.Alt));


            pgLoad.Value = 10;
        }

        private void CheckWorkingDir()
        {
            if(Environment.CurrentDirectory.StartsWith(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP") || Environment.CurrentDirectory.StartsWith(@"\\muenas001\GLW99\ZKuP"))
            {
                //MessageBox.Show("Die Anwendung darf nicht vom Netzlaufwerk gestartet werden!\n\n", "Warnung!", MessageBoxButton.OK, MessageBoxImage.Error);

                XMessageBox box = new XMessageBox("Warnung!", "Die Anwendung darf nicht vom Netzlaufwerk gestartet werden!\n\nDie Anwendung wird automatisch in 10 Sekunden geschlossen", MessageBoxImage.Warning);
                box.ShowDialog();

                //Application.Current.Shutdown();
            }
        }

        private async void CheckVersion()
        {
            try
            {
                var newVersion = new Version(File.ReadAllText(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Version.txt"));
                var oldVersion = new Version(Version);
                var result = newVersion.CompareTo(oldVersion);

                if (result >= 1)
                {
                    //if (Convert.ToDouble(File.ReadAllText(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Version.txt")) > Convert.ToDouble(lblVersion.Text.Split(' ')[1]))
                    //{
                    //if (MessageBox.Show(this, "Neue Version verfügbar!\n\n\n" +
                    //    "Die Anwendung kann nur mit der neuen Version wieder gestartet werden\n" +
                    //    "Die Anwendung wird auf dem Desktop abgelegt, bitte nur diese Datei starten\n" +
                    //    "ZKuP wird nach dem Update automatisch neu gestartet\n\n" +
                    //    "Neue Version herunterladen?", "Neue Version verfügbar!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    //{

                    var file = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.ToString();

                    if (file == @"\\mhb00swfs003v.fv-werke.db.de\GLW99\ProjektDB\ZKuP.exe")
                        file = "";

                    if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") || File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") != File.GetLastWriteTime(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe"))
                    {
                        File.Copy(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", true);

                        System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", $"\"{file}\"");
                        Application.Current.Shutdown();
                        return;
                    }
                    else
                    {
                        System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", $"\"{file}\"");
                        Application.Current.Shutdown();
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.ToString());

                if (MessageBox.Show(this, "Fehler beim Abfragen der Version\n\nDie Anwendung kann genutzt werden\nBitte in einigen Minuten die Anwendung beenden und erneut starten\n\nMöchten Sie sich die detaillierte Fehlermeldung anzeigen lassen?", "Fehler!", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes)
                    MessageBox.Show(this, "Fehlermeldung:\n\n" + ex.Message, "Fehlermeldung", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        bool updateAlreadyAsked = false;
        private void CheckForNewVersion()
        {
            var newVersion = new Version(File.ReadAllText(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Version.txt"));
            var oldVersion = new Version(Version);
            var result = newVersion.CompareTo(oldVersion);

            if (result >= 1)
            {
                var file = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.ToString();

                if (file == @"\\mhb00swfs003v.fv-werke.db.de\GLW99\ProjektDB\ZKuP.exe")
                    file = "";


                if (MessageBox.Show($"Es ist eine neue Version verfügbar\n\nIhre Version: {oldVersion.ToString()}\nNeue Version: {newVersion.ToString()}\n\nDie Aktualisierung dauert ca. 30 Sekunden\nWenn Sie jetzt nicht aktualisieren, wird die neue Version automatisch beim nächsten Start der Anwendung geladen\n\nMöchten Sie jetzt auf die neue Version aktualisieren?", "Neue Version verfügbar!", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") || File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe") != File.GetLastWriteTime(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe"))
                    {
                        File.Copy(@"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\ZKuPUpdater.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", true);

                        System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", $"\"{file}\"");
                        Application.Current.Shutdown();
                        return;
                    }
                    else
                    {
                        System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPUpdater.exe", $"\"{file}\"");
                        Application.Current.Shutdown();
                        return;
                    }
                }
                else updateAlreadyAsked = true;
            }
        }


        private void CheckNotification()
        {
            if (LoggedInRole != Roles.None)
            {
                var path = @"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Notification.txt";

                var text = File.ReadAllText(path).Split('|')[0];

                bool repeat = false;
                if (text.EndsWith("|true")) repeat = true;

                if (text.Length > 0)
                {
                    if (!Settings.GetSettingBool("HinweisShown")) MessageBox.Show(text, "Hinweis", MessageBoxButton.OK, MessageBoxImage.Stop);
                    if (!repeat) Settings.WriteSetting("HinweisShown", true);
                }
                else Settings.WriteSetting("HinweisShown", false);
            }
        }

        private void CheckMaintenance()
        {
            var path = @"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Maintenance.txt";

            var text = File.ReadAllText(path);
            if (text.Length > 0)
            {
                MessageBox.Show(text + "\n\nDie Anwendung wird jetzt wieder geschlossen!", "Wartungsarbeiten", MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }
        }


        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            await Task.Run(() => AuthenticateUser());


            isSecureConn = SQL.IsSecureConnection();
//#if !DEBUG
            Helper.CheckIfMultipleInstances();
//#endif

            double maxheight = this.ActualHeight - 120 - 191;
            double actualheight = this.ActualHeight - 120 - gridBackground.RowDefinitions[1].Height.Value;
            if (actualheight <= 191) gridBackground.RowDefinitions[1].Height = new GridLength(maxheight);

            //gridSpinner.Visibility = Visibility.Collapsed;
            Helper.width = this.MinWidth;
            Helper.height = this.MinHeight;


            connTimer.Interval = TimeSpan.FromSeconds(2);
            connTimer.Tick += ConnTimer_Tick;
            connTimer.Start();

            Helper.CheckScale(this);
            Helper.CheckWindowIsInScreenSpace(this);

        }


        #region Check if Window was moved and released
        private const int WM_ENTERSIZEMOVE = 0x0231;
        private const int WM_EXITSIZEMOVE = 0x0232;

        private Point _startPosition;
        private Size _startSize;


        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource source = (HwndSource)PresentationSource.FromVisual(this);
            source.AddHook(WndProc);
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case WM_ENTERSIZEMOVE:
                    _startPosition = new Point(Left, Top);
                    _startSize = new Size(Width, Height);
                    break;

                case WM_EXITSIZEMOVE:
                    bool sizeChanged = Width != _startSize.Width || Height != _startSize.Height;
                    bool positionChanged = Left != _startPosition.X || Top != _startPosition.Y;

                    if (positionChanged && !sizeChanged)
                    {
                        OnWindowMoveFinished();
                    }
                    break;
            }

            return IntPtr.Zero;
        }

        private void OnWindowMoveFinished()
        {
            Helper.CheckScale(this);
        }
        #endregion



        private async void AuthenticateUser()
        {
            if (!SQL.CheckDeviceConnection())
            {
                MessageBox.Show("Verbindung zum Server fehlgeschlagen\nBitte Netzwerkverbindung prüfen", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                Dispatcher.Invoke(() => Application.Current.Shutdown());
                return;
            }

            if (AuthenticateDomain())
            {
                if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    MessageBox.Show($"Ihr User {Environment.UserName} ist nicht zum Zugriff berechtigt", "Zugriff verweigert");
                    Dispatcher.Invoke(() => Application.Current.Shutdown());
                    return;
                }
                else
                {
                    string auth = "";
                    string role = "";

                    if (!SQL.TestConnection())
                    {
                        return;
                    }

                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 15));

                    auth = await SQL.ReadSingleValueAsync($"SELECT EXISTS(SELECT * FROM {MainWindow.table}.users WHERE `Username` = '{Environment.UserName}')");
                    await Dispatcher.BeginInvoke(new Action(() => SQL.WriteSQL($"REPLACE INTO {MainWindow.table}.apptracker (Username, Version, LastLogin, Online) VALUES ('{Environment.UserName}', '{Version}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', 1)")));

                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 20));

                    if (auth == "1")
                    {
                        role = await SQL.ReadSingleValueAsync($"SELECT Role FROM {MainWindow.table}.users WHERE `Username` = '{Environment.UserName}'");
                        await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 25));
                    }
                    else
                    {
                        //CheckVersion();
                        await Dispatcher.BeginInvoke(new Action(() =>
                        {
                            var res = MessageBox.Show($"Ihr User {Helper.InsertSpaceBeforeUpperCase(Environment.UserName)} ist nicht zum Zugriff berechtigt\n\nMöchten Sie einen Parkausweis beantragen, einen McFit User erstellen oder eine Werksführung buchen?", "Zugriff verweigert", MessageBoxButton.YesNo, MessageBoxImage.Warning);

                            if (res == MessageBoxResult.Yes)
                            {
                                BesucherCreateStart();

                                return;
                            }
                            else if (res == MessageBoxResult.No)
                            {
                                Dispatcher.Invoke(() => Application.Current.Shutdown());
                                return;
                            }

                            Dispatcher.Invoke(() => Application.Current.Shutdown());
                        }));
                        return;
                    }

                    await Dispatcher.BeginInvoke(new Action(() =>
                    {
                        switch (role)
                        {
                            case "0":
                                PfoertnerStart();
                                break;
                            case "1":
                                FFKStart();
                                break;
                            case "2":
                                AdminStart();
                                break;
                            case "3":
                                FFKSasseStart();
                                break;
                            case "4":
                                M2Start();
                                break;
                            case "5":
                                OrganisatorStart();
                                break;
                            case "6":
                                M2_AMStart();
                                break;
                            default:
                                BesucherCreateStart();
                                break;
                        }

                        this.Title = "ZKuP - " + Version + "\tRolle: " + LoggedInRole.ToString().Replace("_", " ");

                    }));

                    //var beInfos = await SQL.ReadListStringTwoColumns($"SELECT flaeche, bereich FROM {MainWindow.table}.`be-belegung`");
                    await Dispatcher.BeginInvoke(new Action(async () =>
                    {
                        var ausgegebenAn = 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);

                        foreach (TextBlock tb in Helper.FindVisualChildren<TextBlock>(BE))//.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 });


                                var x = ausgegebenAn.TryGetValue(parkplatz, out string y);
                                if (ausgegebenAn.ContainsKey(parkplatz) && x && !string.IsNullOrWhiteSpace(y))
                                    sp.Children.Add(new TextBlock() { Text = $"Ausgegeben an {y}" });

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

                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 40));

                    await getToday();
                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 60));

                    getHinweis();
                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 70));

                    await getPark();
                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 80));

                    await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.zutritte WHERE Zutritt < current_date() - INTERVAL 30 DAY");
                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 85));

                    await getZutritte();
                    //overv = SQL.ReadSQL("SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv).Result;
                    await Dispatcher.BeginInvoke(new Action(() => pgLoad.Value = 100));
                    //Overviews = DataTableToOverview(overv);
                    await getMcFitCards();

                    await getFahrzeuge();


                    Thread.Sleep(200);

                    await Dispatcher.BeginInvoke(new Action(() =>
                    {
                        getBikes();

                        dgOverview.DataContext = overv;


                        dgOverview.Items.SortDescriptions.Clear();
                        dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
                        dgOverview.Items.Refresh();

                        //var gif = XamlAnimatedGif.AnimationBehavior.GetAnimator(imgLoading);
                        //if (gif != null)
                        //{
                        //    gif.Pause();
                        //}
                        //imgLoading.Visibility = Visibility.Collapsed;

                        this.Height = Settings.GetSettingDouble("Height");
                        this.Width = Settings.GetSettingDouble("Width");
                        this.Left = Settings.GetSettingDouble("Left");
                        this.Top = Settings.GetSettingDouble("Top");

                        var ws = Settings.GetSetting("WindowState");
#pragma warning disable CS0252
                        this.WindowState = ws == "" ? WindowState.Normal : (WindowState)ws;
#pragma warning restore CS0252
                        //double ratio = Settings.GetSettingDouble("ColumnRatio");

                        // Gespeicherte Werte laden
                        double col1Width = Settings.GetSettingDouble("LeftColumn");
                        double col2Width = Settings.GetSettingDouble("RightColumn");

                        // Column-Breiten setzen
                        gridToday.ColumnDefinitions[0].Width = new GridLength(col1Width, GridUnitType.Star);
                        gridToday.ColumnDefinitions[2].Width = new GridLength(col2Width, GridUnitType.Star);
                        // Index 1 ist der GridSplitter mit Auto-Breite


                        ReadyToSavePosition = true;
                        gridSpinner.Visibility = Visibility.Hidden;



                        reloadTimer.Interval = TimeSpan.FromSeconds(10);
                        reloadTimer.Tick += ReloadTimer_Tick;
                        reloadTimer.Start();

                        //reloadTimerHinweis.Interval = TimeSpan.FromSeconds(10);
                        //reloadTimerHinweis.Tick += ReloadTimerHinweis_Tick;
                        //reloadTimerHinweis.Start();

                        checkUpdateTimer.Interval = TimeSpan.FromMinutes(5);
                        checkUpdateTimer.Tick += CheckUpdateTimer_Tick;
                        checkUpdateTimer.Start();




                        if ((LoggedInRole == Roles.Admin || LoggedInRole == Roles.M2_AM) && Settings.GetSettingBool("ShowParkcardAccept"))
                        {
                            if (SQL.RowExists("parkausweise", "Genehmigt", "0").Result == true)
                            {
                                if (MessageBox.Show(this, "Es liegen zu genehmigende Parkkartenanträge vor!\n\nMöchten Sie diese jetzt überprüfen?", "Neue Anträge", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                                {
                                    GrantParkausweis gPa = new GrantParkausweis();
                                    gPa.Owner = this;
                                    gPa.Show();
                                }
                            }
                        }
                        else if ((LoggedInRole == Roles.Admin || LoggedInRole == Roles.M2_AM) && Settings.GetSettingBool("ShowParkcardPrint"))
                        {
                            if (SQL.RowExists("parkausweise", "Genehmigt = '1' AND Gedruckt", "0").Result == true)
                            {
                                if (MessageBox.Show(this, "Es liegen zu druckende Parkkarten vor!\n\nMöchten Sie diese jetzt überprüfen?", "Neue Parkkarten", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                                {
                                    PrintParkausweis pPa = new PrintParkausweis();
                                    pPa.Owner = this;
                                    pPa.Show();
                                }
                            }
                        }
                    }));

                }

                Dispatcher.Invoke(() => Helper.FindVisualChildren<Button>(dgToday, "btnInfo").ToList().ForEach(q =>
                {
                    q.Click -= BtnInfo_Click;
                    q.Click += BtnInfo_Click;
                }));
            }
            else
            {
                MessageBox.Show("User nicht in der Domäne aktiviert");
                Dispatcher.Invoke(() => Application.Current.Shutdown());
                return;
            }
        }

        private bool AuthenticateDomain()
        {
            try
            {

                using (var domainContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
                {
                    using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, Environment.UserName))
                    {
                        if (foundUser.Enabled.HasValue)
                        {
                            return (bool)foundUser.Enabled;
                        }
                        else
                        {
                            return false; //or false depending what result you want in the case of Enabled being NULL
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToString().Contains("password is incorrect"))
                {
                    MessageBox.Show($"Die Authentifizierung Ihres Users gegen die Domäne ist fehlgeschlagen\n\n" +
                            $"Fehlermeldung:\n" +
                            $"{ex.Message}\n\n",
                            "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);

                    MessageBox.Show($"Die Anwendung wird jetzt versuchen zur Domäne zu verbinden\n\n" +
                            $"Wenn eine Passwortabfrage erscheint, bitte BKU Benutzer und Passwort eingeben\n" +
                            $"Ist der Vorgang erfolgreich, kann die Anwendung anschließend wieder gestartet werden,\n" +
                            $"falls nicht, wenden Sie sich bitte an den Administrator",
                            "Erneute Authentifizierung", MessageBoxButton.OK, MessageBoxImage.Error);



                    var p = new ProcessStartInfo("explorer.exe");
                    p.Arguments = "\\\\mhb00swfs003v.fv-werke.db.de\\GLW99\\ZKuP\\";
                    p.CreateNoWindow = true;
                    p.UseShellExecute = false;

                    var process = Process.Start(p);

                    process.CloseMainWindow();

                    Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ZKuP.exe");
                }
                else
                {
                    MessageBox.Show($"Die Authentifizierung Ihres Users gegen die Domäne ist fehlgeschlagen\n\n" +
                        $"Fehlermeldung:\n" +
                        $"{ex.Message}\n\n" +
                        $"Die Anwendung wird geschlossen.\n" +
                        $"Bitte wenden Sie sich an den Administrator",
                        "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                Dispatcher.Invoke(() => Application.Current.Shutdown());

                return false;
            }
        }

        private async void AdminStart()
        {
            LoggedInRole = Roles.Admin;

            //CheckVersion();

            tabAdmin.Visibility = Visibility.Visible;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Visible;
            tabSonstiges.Visibility = Visibility.Visible;
            

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Visible;
            gridLieferanten.Visibility = Visibility.Visible;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnManageUsers.Visibility = Visibility.Visible;
            btnCreateVisitor.Visibility = Visibility.Visible;
            btnCreateFirma.Visibility = Visibility.Visible;
            btnManageAsp.Visibility = Visibility.Visible;
            btnKarten.Visibility = Visibility.Visible;
            btnSignatures.Visibility = Visibility.Visible;
            btnDelivery.Visibility = Visibility.Visible;
            //btnNew.Visibility = Visibility.Visible;
            btnCreateDeliveries.Visibility = Visibility.Visible;
            btnEmergency.Visibility = Visibility.Visible;
            btnBelegung.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Visible;
            btnBE.Visibility = Visibility.Visible;
            btnApproveFzg.Visibility = Visibility.Visible;

            btnCheckParkausweis.Visibility = Visibility.Visible;
            btnCreateParkausweis.Visibility = Visibility.Visible;
            //btnCreateSpecialParkausweis.Visibility = Visibility.Visible;
            btnGrantParkausweis.Visibility = Visibility.Visible;
            btnListParkausweis.Visibility = Visibility.Visible;
            btnPrintParkausweis.Visibility = Visibility.Visible;

            btnCheckKennzeichen.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Visible;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            //btnSetHinweis.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;

            columnFzg.Visibility = Visibility.Visible;
            columnBeginn.Visibility = Visibility.Visible;
            columnEnde.Visibility = Visibility.Visible;
            btnMcFitSign.Visibility = Visibility.Visible;
            btnNotifications.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Admin");
            // something that only an admin user should be able to do

            if (Environment.UserName == "RainerGaertner")
            {
                btnIvoBackground.Visibility = Visibility.Visible;
                canvasIvo.Visibility = Visibility.Visible;
            }
                      
            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));
            //CommandBindings.Add(new CommandBinding(skullWindow, MainWindow_SkullWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

#if DEBUG
            //ausfahrtTimer.Tick += AusfahrtTimer_Tick;
            //ausfahrtTimer.Interval = TimeSpan.FromMinutes(0.1);
            //ausfahrtTimer.Start();
#endif

            tcMainMenu.SelectedIndex = 4;
        }

        private async void FFKSasseStart()
        {
            LoggedInRole = Roles.FFK_Sasse;

            //CheckVersion();
            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Visible;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnCreateFirma.Visibility = Visibility.Visible;
            btnManageAsp.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnBelegung.Visibility = Visibility.Collapsed;
            btnBE.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCreateParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Editor");
            // something that only an editor user should be able to do
            btnMcFitSign.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Visible;

            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 1;
        }

        private void FFKStart()
        {
            LoggedInRole = Roles.FFK;

            //CheckVersion();

            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Visible;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnCreateFirma.Visibility = Visibility.Visible;
            btnManageAsp.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnBelegung.Visibility = Visibility.Collapsed;
            btnBE.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCreateParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Editor");
            // something that only an editor user should be able to do
            btnMcFitSign.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Visible;

            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 1;
        }

        private void M2Start()
        {
            LoggedInRole = Roles.M2;

            //CheckVersion();

            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Visible;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnCreateFirma.Visibility = Visibility.Visible;
            btnManageAsp.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnBelegung.Visibility = Visibility.Visible;
            btnBE.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCreateParkausweis.Visibility = Visibility.Visible; 
            btnCheckParkausweis.Visibility = Visibility.Visible;
            //btnCreateSpecialParkausweis.Visibility = Visibility.Visible;
            btnGrantParkausweis.Visibility = Visibility.Visible;
            btnListParkausweis.Visibility = Visibility.Visible;
            btnPrintParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Editor");
            // something that only an editor user should be able to do
            btnMcFitSign.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Visible;

            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 1;
        }

        private void M2_AMStart()
        {
            LoggedInRole = Roles.M2_AM;

            //CheckVersion();

            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Visible;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnCreateFirma.Visibility = Visibility.Visible;
            btnManageAsp.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnBelegung.Visibility = Visibility.Visible;
            btnBE.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCreateParkausweis.Visibility = Visibility.Visible;
            btnCheckParkausweis.Visibility = Visibility.Visible;
            //btnCreateSpecialParkausweis.Visibility = Visibility.Visible;
            btnGrantParkausweis.Visibility = Visibility.Visible;
            btnListParkausweis.Visibility = Visibility.Visible;
            btnPrintParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Editor");
            // something that only an editor user should be able to do
            btnMcFitSign.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Visible;

            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 1;
        }
        private void PfoertnerStart()
        {
            LoggedInRole = Roles.Pförtner;

            //CheckVersion();
            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Visible;
            tabSonstiges.Visibility = Visibility.Visible;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            gridArrived.Visibility = Visibility.Visible;

            gridBike.Visibility = Visibility.Visible;
            gridLieferanten.Visibility = Visibility.Visible;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Visible;
            tbSearchArrived.Visibility = Visibility.Visible;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Visible;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnCreateFirma.Visibility = Visibility.Collapsed;
            btnManageAsp.Visibility = Visibility.Collapsed;
            btnKarten.Visibility = Visibility.Visible;
            //btnNew.Visibility = Visibility.Visible;
            btnDelivery.Visibility = Visibility.Visible;
            btnCreateDeliveries.Visibility = Visibility.Visible;
            btnEmergency.Visibility = Visibility.Visible;
            btnBE.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Visible;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCheckParkausweis.Visibility = Visibility.Visible;
            //btnPrintParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Visible;
            gridSplitterArrows.Visibility = Visibility.Visible;
            gridSplitterLine.Visibility = Visibility.Visible;
            //MessageBox.Show("Sie sind Pförtner");
            // something that only an pförtner user should be able to do
            btnMcFitSign.Visibility = Visibility.Collapsed;
            //btnNotification.Visibility = Visibility.Collapsed;


            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 2;

            ausfahrtTimer.Tick += AusfahrtTimer_Tick;
            ausfahrtTimer.Interval = TimeSpan.FromMinutes(1);
            ausfahrtTimer.Start();
        }

        private void OrganisatorStart()
        {
            LoggedInRole = Roles.Organisator;

            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Visible;
            tabPark.Visibility = Visibility.Visible;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Visible;
            dgToday.Visibility = Visibility.Collapsed;
            lblAnkunftHeuteFirmen.Visibility = Visibility.Collapsed;
            Grid.SetColumn(lblAnkunftHeuteBesucher, 0);
            Grid.SetColumn(dgTodayBesucher, 0);
            Grid.SetColumnSpan(dgTodayBesucher, 3);
            gridSplitterVertical.Visibility = Visibility.Collapsed;
            gridSplitterArrowsVertical.Visibility = Visibility.Collapsed;

            BesuchP.Visibility = Visibility.Collapsed;
            BE.Visibility = Visibility.Collapsed;

            Main.Visibility = Visibility.Visible;
            gridToday.Visibility = Visibility.Visible;
            
            gridArrived.Visibility = Visibility.Collapsed;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Visible;
            tbSearch.Visibility = Visibility.Visible;
            lblSearchArrived.Visibility = Visibility.Collapsed;
            tbSearchArrived.Visibility = Visibility.Collapsed;
            btnClearSearch.Visibility = Visibility.Visible;
            btnClearSearchArrived.Visibility = Visibility.Collapsed;

            btnCreateVisitor.Visibility = Visibility.Visible;
            btnManageUsers.Visibility = Visibility.Collapsed;
            btnCreateFirma.Visibility = Visibility.Collapsed;
            btnManageAsp.Visibility = Visibility.Visible;
            btnKarten.Visibility = Visibility.Collapsed;
            //btnNew.Visibility = Visibility.Visible;
            btnDelivery.Visibility = Visibility.Collapsed;
            btnCreateDeliveries.Visibility = Visibility.Collapsed;
            btnEmergency.Visibility = Visibility.Collapsed;
            btnBE.Visibility = Visibility.Collapsed;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            btnCheckParkausweis.Visibility = Visibility.Collapsed;
            btnCreateParkausweis.Visibility = Visibility.Visible;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Visible;

            gridSplitter.Visibility = Visibility.Collapsed;
            gridSplitterArrows.Visibility = Visibility.Collapsed;
            gridSplitterLine.Visibility = Visibility.Collapsed;
            //MessageBox.Show("Sie sind Pförtner");
            // something that only an pförtner user should be able to do
            btnMcFitSign.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Collapsed;


            CommandBindings.Add(new CommandBinding(resetWindow, MainWindow_ResetWindow));

            ChangeTheme(Settings.GetSettingBool("DarkMode"));
            ChangeAccent(Settings.GetSettingString("Accent"));
            //ChangeTheme(Properties.Settings.Default.DarkMode);
            //ChangeAccent(Properties.Settings.Default.Accent);

            tcMainMenu.SelectedIndex = 1;
        }



        private void BesucherCreateStart()
        {
            LoggedInRole = Roles.None;

            tabAdmin.Visibility = Visibility.Collapsed;
            tabFirmBesAsp.Visibility = Visibility.Collapsed;
            tabPark.Visibility = Visibility.Collapsed;
            tabPfoertner.Visibility = Visibility.Collapsed;
            tabSonstiges.Visibility = Visibility.Collapsed;

            Main.Visibility = Visibility.Collapsed;

            this.Width = 700;
            this.Height = 700;
            this.ResizeMode = ResizeMode.NoResize;

            Main.Visibility = Visibility.Collapsed;
            gridToday.Visibility = Visibility.Collapsed;
            gridArrived.Visibility = Visibility.Collapsed;

            gridBike.Visibility = Visibility.Collapsed;
            gridLieferanten.Visibility = Visibility.Collapsed;

            UserCreate.Visibility = Visibility.Visible;
            btnResetLists.Visibility = Visibility.Collapsed;
            gridSplitter.Visibility = Visibility.Collapsed;
            gridSplitterArrows.Visibility = Visibility.Collapsed;
            gridSplitterLine.Visibility = Visibility.Collapsed;
            lblResetLists.Visibility = Visibility.Collapsed;
            btnResetLists.Visibility = Visibility.Collapsed;

            btnSettings.Visibility = Visibility.Collapsed;
            btnArrivalsOverview.Visibility = Visibility.Collapsed;

            gridSplitter.Visibility = Visibility.Collapsed;
            gridSplitterArrows.Visibility = Visibility.Collapsed;
            gridSplitterLine.Visibility = Visibility.Collapsed;
            //btnResetListsMain.Visibility = Visibility.Collapsed;

            gridSpinner.Visibility = Visibility.Collapsed;
            btnMcFitSign.Visibility = Visibility.Visible;
            btnKartenTausch.Visibility = Visibility.Collapsed;
            btnApproveFzg.Visibility = Visibility.Collapsed;

            //lblSearch.Visibility = Visibility.Collapsed;
            tbSearch.Visibility = Visibility.Collapsed;
            btnClearSearch.Visibility = Visibility.Collapsed;
            lblSearchArrived.Visibility = Visibility.Collapsed;
            tbSearchArrived.Visibility = Visibility.Collapsed;
            btnClearSearchArrived.Visibility = Visibility.Collapsed;

            lblmcfit2.Visibility = Visibility.Visible;
            //btnNotification.Visibility = Visibility.Collapsed;

        }


        private void MainWindow_ResetWindow(object sender, ExecutedRoutedEventArgs e)
        {
            this.WindowState = WindowState.Normal;

            this.Left = 0;
            this.Top = 0;

            this.Width = 1624;
            this.Height = 747;
        }

        private void MainWindow_SkullWindow(object sender, ExecutedRoutedEventArgs e)
        {
            canvasIvo.Visibility = canvasIvo.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        }

        DateTime lastEntryZutritte = Convert.ToDateTime("01.01.1901");
        DateTime temp = Convert.ToDateTime("01.01.1901");

        private async void ReloadTimer_Tick(object sender, EventArgs e)
        {
            try { await Task.Run(() => getToday()); }                
            catch (Exception ex) { Log.WriteLog("getToday():   " + ex.Message); }

            try { await Task.Run(() => getZutritte()); }
            catch (Exception ex) { Log.WriteLog("getZutritte():   " + ex.Message); }

            try { await Task.Run(() => getPark()); }
            catch (Exception ex) { Log.WriteLog("getPark():   " + ex.Message); }

            try { await Task.Run(() => getMcFitCards()); }
            catch (Exception ex) { Log.WriteLog("getMcFitCards():   " + ex.Message); }

            try { await Task.Run(() => getFahrzeuge()); }
            catch (Exception ex) { Log.WriteLog("getFahrzeuge():   " + ex.Message); }

            try { await Task.Run(() => getBikes()); }
            catch (Exception ex) { Log.WriteLog("getBikes():   " + ex.Message); }
        }

        private void ReloadTimerHinweis_Tick(object sender, EventArgs e)
        {
            getHinweis();

            //var hwnd = new System.Windows.Interop.WindowInteropHelper(this).EnsureHandle();
            //var currentMonitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST);
            //var primaryMonitor = NativeMethods.MonitorFromWindow(IntPtr.Zero, NativeMethods.MONITOR_DEFAULTTOPRIMARY);
            //var isInPrimary = currentMonitor == primaryMonitor;

            double fullwidth = 0;
            double fullheight = 0;

            
            foreach (var s in WpfScreenHelper.Screen.AllScreens)
            {
                fullwidth += s.Bounds.Width;
                fullheight += s.Bounds.Height;
            }


            if (this.Left >= fullwidth - 100 || this.Top >= fullheight - 50 || this.Left < -(this.Width * 0.9) || this.Top < -(this.Height * 0.9))
                MainWindow_ResetWindow(null,  null);

            //System.Diagnostics.Debug.WriteLine($"{isInPrimary}   {fullwidth}x{fullheight}   {this.Left}x{this.Top}");
        }


        private void CheckUpdateTimer_Tick(object sender, EventArgs e)
        {
            if (!updateAlreadyAsked)
            {
                CheckForNewVersion();
            }

            var path = @"\\mhb00swfs003v.fv-werke.db.de\GLW99\ZKuP\Maintenance.txt";

            var text = File.ReadAllText(path).Split('|')[0];

            if (text.Length > 0)
            {
                XMessageBox box = new XMessageBox("Wartungsmodus", "Der Wartungsmodus wurde eingeleitet!\n\n" +
                                                                    "Bitte schließen Sie Ihre Arbeit ab und beenden Sie die Anwendung\n\n" +
                                                                    "Die Anwendung wird in 60 Sekunden automatisch beendet",
                                                                    MessageBoxImage.Exclamation, true, 60);
            }
                //MessageBox.Show("Der Wartungsmodus wurde eingeleitet!\n\n" +
                //    "Bitte schließen Sie Ihre Arbeit ab und beenden Sie die Anwendung\n\n" +
                //    "Die Anwendung wird in 60 Sekunden automatisch beendet");
        }

        List<string> notifiedKennzeichen = new List<string>();
        Dictionary<DateTime, string> renotifyKennzeichen = new Dictionary<DateTime, string>();
        private async void AusfahrtTimer_Tick(object sender, EventArgs e)
        {
                var rr = "";
            try
            {

                var result = await Task.Run(() => SQL.ReadListStringMultipleColumns($"SELECT arrivalTime, fzgType, firma, fahrer, kennzeichen, telFahrer FROM {MainWindow.table}.fzgTime WHERE " +
                    $"firma NOT LIKE '%DB Energie%' AND " +
                    $"firma NOT LIKE '%DB InfraGO%' AND " +
                    $"firma NOT LIKE '%DB KT%' AND " +
                    $"firma <> 'Gerätewagen'", 6));

                string message = "";

                if (result.Count > 0)
                {
                    foreach (var r in result)
                    {
                        var s = r.Split(';');
                        rr = r;

                        if (s.Length > 5)
                        {
                            switch (s[1].ToString())
                            {
                                case "LKWLang":
                                    if ((DateTime.Now - Convert.ToDateTime(s[0])) > TimeSpan.FromMinutes(60) && !notifiedKennzeichen.Contains(s[4]))
                                    {
                                        message += $"Firma:\t\t{s[2]}\nFahrer:\t\t{s[3]}\nKennzeichen:\t{s[4]}\nTelefon Fahrer:\t{s[5]}\nTyp:\t\t{s[1]}\n\n";
                                    }
                                    break;
                                case "LKW":
                                    if ((DateTime.Now - Convert.ToDateTime(s[0])) > TimeSpan.FromMinutes(60) && !notifiedKennzeichen.Contains(s[4]))
                                    {
                                        message += $"Firma:\t\t{s[2]}\nFahrer:\t\t{s[3]}\nKennzeichen:\t{s[4]}\nTelefon Fahrer:\t{s[5]}\nTyp:\t\t{s[1]}\n\n";
                                    }
                                    break;
                                case "Sprinter":
                                    if ((DateTime.Now - Convert.ToDateTime(s[0])) > TimeSpan.FromMinutes(30) && !notifiedKennzeichen.Contains(s[4]))
                                    {
                                        message += $"Firma:\t\t{s[2]}\nFahrer:\t\t{s[3]}\nKennzeichen:\t{s[4]}\nTelefon Fahrer:\t{s[5]}\nTyp:\t\t{s[1]}\n\n";
                                    }
                                    break;
                                case "PKW":
                                    if ((DateTime.Now - Convert.ToDateTime(s[0])) > TimeSpan.FromMinutes(30) && !notifiedKennzeichen.Contains(s[4]))
                                    {
                                        message += $"Firma:\t\t{s[2]}\nFahrer:\t\t{s[3]}\nKennzeichen:\t{s[4]}\nTelefon Fahrer:\t{s[5]}\nTyp:\t\t{s[1]}\n\n";
                                    }
                                    break;
                            }
                        }
                        else Log.WriteLog("MessageArray to short:\n\n" + r);
                    }

                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        MessageBox.Show("Folgende Fahrzeuge sind bereits zu lang im Werk:\n\n" + message + "Bitte prüfen Sie warum die Fahrzeuge noch im Werk sind", "Fahrzeuge prüfen", MessageBoxButton.OK, MessageBoxImage.Information);

                        foreach (var r in result)
                        {
                            if(r.Split(';').Length > 5)
                            notifiedKennzeichen.Add(r.Split(';')[4]);

                            if (!renotifyKennzeichen.ContainsValue(r.Split(';')[4]) && !renotifyKennzeichen.ContainsKey(DateTime.Now))
                                renotifyKennzeichen.Add(DateTime.Now, r.Split(';')[4]);
                        }
                    }
                }

                List<DateTime> remov = new List<DateTime>();
                foreach (var re in renotifyKennzeichen)
                {
                    if (notifiedKennzeichen.Contains(re.Value) && (DateTime.Now - re.Key) > TimeSpan.FromMinutes(30))
                    {
                        var firmen = await SQL.ReadListStringMultipleColumns($"SELECT arrivalTime, fzgType, firma, fahrer, kennzeichen, telFahrer FROM {MainWindow.table}.fzgTime WHERE kennzeichen = '{re.Value}'", 6);
                        if (firmen.Count > 0)
                        {
                            var firma = firmen.First().Split(';');
                            if (firma.Length > 5)
                            {
                                MessageBox.Show("Folgendes Fahrzeug ist immer noch im Werk (> 90 min):\n\n" + $"Firma:\t\t{firma[2]}\nFahrer:\t\t{firma[3]}\nKennzeichen:\t{firma[4]}\nTelefon Fahrer:\t{firma[5]}\nTyp:\t\t{firma[1]}\n\n" + "Bitte prüfen Sie warum das Fahrzeug noch im Werk ist", "Fahrzeug prüfen", MessageBoxButton.OK, MessageBoxImage.Information);
                                remov.Add(re.Key);
                            }
                        }
                    }
                }

                foreach (var r in remov)
                    renotifyKennzeichen.Remove(r);

            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.ToString() + $"\n\nValues:\n\n{rr}");
            }
        }


        private void ConnTimer_Tick(object sender, EventArgs e)
        {
            CheckConnection();
        }

        bool lastConn = false;
        bool lastConnSecure = false;
        bool connMsg = true;
        private async Task CheckConnection(bool first = false)
        {
            MySqlConnectionChecker.ConnectionResult conn = new MySqlConnectionChecker.ConnectionResult();

            if (first)
                conn = await MySqlConnectionChecker.CheckConnectionAsync(); //SQL.CheckOnline();
            else
                await Task.Run(async () => conn = await MySqlConnectionChecker.CheckConnectionAsync());

            if (conn.IsConnected)
            {
                if (conn.IsConnected != lastConn || isSecureConn != lastConnSecure)
                {
                    //imgConnection.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                    //            + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                    //            + ";component/"
                    //            + $"Resources/ConnectedSecure.png", UriKind.Absolute));
                    imgConnection.Source = (ImageSource)this.FindResource("ConnectedIcon");

                    imgConnection.ToolTip = $"Verbindung OK";

                    (this.Resources["sbConnection"] as System.Windows.Media.Animation.Storyboard).Begin();
                    (this.Resources["sbConnection"] as System.Windows.Media.Animation.Storyboard).Stop();
                    lastConn = conn.IsConnected;


                    if (isSecureConn)
                    {
                        lastConnSecure = isSecureConn;
                        imgConnection.ToolTip += $" und gesichert";
                        imgSecureConn.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        lastConnSecure = isSecureConn;
                        imgConnection.ToolTip = $"Verbindung OK";
                        imgSecureConn.Visibility = Visibility.Collapsed;
                    }
                }
            }
            else
            {
                await Log.WriteLog(conn.Message);

                if (!Helper.IsVPNConnected())
                {
                    if (connMsg)
                    {
                        connMsg = false;

                        MessageBox.Show("Sie haben keine Verbindung zur Datenbank und das DB VPN 'Ivanti Secure Access (ehem. Pulse Secure)' ist nicht verbunden\n\n" +
                                        "Befinden Sie sich außerhalb des BKU Netzes, bitte die Verbindung zum VPN sicherstellen\n\n" +
                                        "Nach Herstellen der Verbindung erneut starten\n", "VPN verbunden?", MessageBoxButton.OK, MessageBoxImage.Information);/*"Die Anwendung wird jetzt geschlossen"*/
                    }

                    //Application.Current.Shutdown();
                    //Environment.Exit(0);
                }
            }

            if (!conn.IsConnected && conn.IsConnected != lastConn)
            {
                //imgConnection.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                //    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                //    + ";component/"
                //    + $"Resources/Disconnected.png", UriKind.Absolute));
                imgConnection.Source = (ImageSource)this.FindResource("NotConnectedIcon");
                imgSecureConn.Visibility = Visibility.Collapsed;

                imgConnection.ToolTip = $"Verbindung zum Server unterbrochen\n\nEs sind keine Änderungen oder Abfragen möglich";

                (this.Resources["sbConnection"] as System.Windows.Media.Animation.Storyboard).Begin();
                lastConn = conn.IsConnected;

                MessageBox.Show($"Fehler bei der Verbindung zur Datenbank\n\nException: {conn.Exception}");
            }
        }
        

        DateTime lastChange = DateTime.MinValue;
        private async Task getToday()
        {            
            //bool changeTable = false;

            List<string> dates = new List<string>();
            dates = await SQL.ReadListString($"SELECT timestamp FROM {MainWindow.table}.changes ORDER BY timestamp DESC");
            var date = Convert.ToDateTime(dates.First());

            if (date != lastChange)
            {
                lastChange = date;

                if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner || LoggedInRole == Roles.M2_AM)
                {
                    DataTable tempFirm = await SQL.ReadSQL($"Select * FROM {MainWindow.table}.firmen where Arbeitsbeginn <= current_date() AND Arbeitsende >= current_date()");/*, tempFirm*/
                    DataTable tempBesuch = await SQL.ReadSQL($"SELECT idbesucher, concat('Besucher: ', Name) AS Name, Verantwortlicher_MA AS Verantwortlicher_MA_Firma,Tel_Nr_Besucher AS Tel_Nr_Verantwortlicher_Firma,Anzahl_Begleitpersonen,Besuchstag,Grund_des_Besuchs,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern,Kleine_Unterweisung_bis,Oertlichkeit FROM {MainWindow.table}.besucher WHERE Besuchstag = current_date()");/*, tempBesuch*/
                    DataTable tempFamily = await SQL.ReadSQL($"SELECT idfamily,concat('Führung: ', Name) AS Name, Name AS Verantwortlicher_MA_Firma, Name AS Ansprechpartner_Intern,TelNr AS Tel_Nr_Verantwortlicher_Firma FROM {MainWindow.table}.family WHERE `Date` = '{DateTime.Now.Date.ToString("yyyy-MM-dd")}'");


                    Dispatcher.Invoke(() => Helper.FindVisualChildren<Button>(dgToday, "btnInfo").ToList().ForEach(q => q.Click -= BtnInfo_Click));

                    todayFirm = tempFirm;
                    todayBesuch = tempBesuch;
                    todayFamily = tempFamily;
                }
                else
                {
                    DataTable tempFirm = await SQL.ReadSQL($"Select * FROM {MainWindow.table}.firmen where (Arbeitsbeginn <= current_date() AND Arbeitsende >= current_date()) AND (Ersteller = '{Environment.UserName}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                        $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}')");/*, todayFirm*/
                    DataTable tempBesuch = await SQL.ReadSQL($"SELECT idbesucher, concat('Besucher: ', Name) AS Name, Verantwortlicher_MA AS Verantwortlicher_MA_Firma,Tel_Nr_Besucher AS Tel_Nr_Verantwortlicher_Firma,Anzahl_Begleitpersonen,Besuchstag,Grund_des_Besuchs,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern,Kleine_Unterweisung_bis,Oertlichkeit FROM {MainWindow.table}.besucher WHERE Besuchstag = current_date() AND (Ersteller = '{Environment.UserName}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                        $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                        $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}')");/*, todayBesuch*/
                    DataTable tempFamily = await SQL.ReadSQL($"SELECT concat('Führung: ', Name) AS Name, Name AS Verantwortlicher_MA_Firma, Name AS Ansprechpartner_Intern,TelNr AS Tel_Nr_Verantwortlicher_Firma FROM {MainWindow.table}.family WHERE `Date` = '{DateTime.Now.Date.ToString("yyyy-MM-dd")}' AND `User` = '{Environment.UserName}'");


                    Dispatcher.Invoke(() => Helper.FindVisualChildren<Button>(dgToday, "btnInfo").ToList().ForEach(q => q.Click -= BtnInfo_Click));

                    todayFirm = tempFirm;
                    todayBesuch = tempBesuch;
                    todayFamily = tempFamily;

                }

                //if (changeTable)
                //{
                    var firmview = todayFirm.DefaultView;

                    if (firmview.Table.Columns.Contains("Name"))
                    {
                        firmview.Sort = "Name";
                        todayFirm = firmview.ToTable();
                    }


                    var besuchview = todayBesuch.DefaultView;

                    if (besuchview.Table.Columns.Contains("Name"))
                    {
                        besuchview.Sort = "Name";
                        todayBesuch = besuchview.ToTable();
                    }


                    var familyview = todayFamily.DefaultView;

                    if (familyview.Table.Columns.Contains("Name"))
                    {
                        familyview.Sort = "Name";
                        todayFamily = familyview.ToTable();
                    }

                    todayBesuch.Merge(todayFamily);
                    //todayFirm.Merge(todayBesuch);
                    //todayFirm.Merge(todayFamily);

                    await Dispatcher.BeginInvoke(new Action(() =>
                    {
                        dgToday.DataContext = todayFirm;
                        dgTodayBesucher.DataContext = todayBesuch;
                    }));
                //}
            }
            Dispatcher.Invoke(() => Helper.FindVisualChildren<Button>(dgToday, "btnInfo").ToList().ForEach(q =>
            {
                q.Click -= BtnInfo_Click;
                q.Click += BtnInfo_Click;
            }));
        }



        private async Task getZutritte()
        {
            try
            {
                if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner || LoggedInRole == Roles.M2_AM)
                {

                    if (lastEntryZutritte == temp)
                    {
                        overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

                        if (!DateTime.TryParse(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"), out lastEntryZutritte))
                            lastEntryZutritte = DateTime.MinValue;
                    }
                    else
                    {
                        DateTime sqlTime = DateTime.MinValue;
                        if (!DateTime.TryParse(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"), out sqlTime)) //Read newest Zutritt TimeStamp                                                                                                                                                      
                            sqlTime = DateTime.MaxValue;                                                                                              //if not parseable write Max Time as Failsafe


                        if (lastEntryZutritte < sqlTime)
                        {
                            DataTable temp = new DataTable("temp");

                            temp = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt > '{lastEntryZutritte.ToString("yyyy-MM-dd HH:mm:ss")}'", temp);
                            if (!DateTime.TryParse(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"), out lastEntryZutritte))
                                lastEntryZutritte = DateTime.MaxValue;

                            Dispatcher.Invoke(() => overv.Merge(temp));


                            ShowToast(temp);
                        }
                    }
                }
                else
                {
                    var vertAspName = SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");
                    var nameAspVert = SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");

                    if (lastEntryZutritte == temp)
                    {
                        overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY AND (idFirma_Besucher IN (select idfirmen from {MainWindow.table}.firmen where Ersteller = '{Environment.UserName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                            $"OR Ersteller = '{vertAspName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                            $"OR Ersteller = '{nameAspVert}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                            $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}') " +
                            $"OR idFirma_Besucher IN (select idbesucher from {MainWindow.table}.besucher where Ersteller = '{Environment.UserName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                            $"OR Ersteller = '{vertAspName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                            $"OR Ersteller = '{nameAspVert}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                            $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'))", overv);

                        lastEntryZutritte = Convert.ToDateTime(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"));
                    }
                    else
                    {
                        DateTime sqlTime = Convert.ToDateTime(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"));
                        if (lastEntryZutritte < sqlTime)
                        {
                            DataTable temp = new DataTable("temp");

                            temp = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt > '{lastEntryZutritte.ToString("yyyy-MM-dd HH:mm:ss")}' AND (idFirma_Besucher IN (select idfirmen from {MainWindow.table}.firmen where Ersteller = '{Environment.UserName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                            $"OR Ersteller = '{vertAspName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                            $"OR Ersteller = '{nameAspVert}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                            $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}') " +
                            $"OR idFirma_Besucher IN (select idbesucher from {MainWindow.table}.besucher where Ersteller = '{Environment.UserName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                            $"OR Ersteller = '{vertAspName}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                            $"OR Ersteller = '{nameAspVert}' " +
                            $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                            $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'))", temp);


                            lastEntryZutritte = Convert.ToDateTime(await SQL.ReadSingleValueAsync($"SELECT MAX(Zutritt) FROM {MainWindow.table}.zutritte"));

                            Dispatcher.Invoke(() => overv.Merge(temp));

                            ShowToast(temp);
                        }
                    }
                }

                //Dispatcher.Invoke(() => dgOverview.Columns.FirstOrDefault(c => c.Header.ToString() == "Zutritt").SortDirection = ListSortDirection.Descending);
                await Dispatcher.InvokeAsync((() =>
                {
                    if (dgOverview.CurrentItem != null)
                    {
                        if ((dgOverview.CurrentItem as DataRowView).IsEdit == true) return;

                        dgOverview.Items.SortDescriptions.Clear();
                        dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
                        dgOverview.Items.Refresh();
                    }
                }));
            }
            catch (Exception ex)
            {
                Log.WriteLog($"getZutritte:   {ex.ToString()}");
//#warning No Release  Do not throw
//                throw;
            }
        }

        private async void getHinweis()
        {
            //if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner)
            //{
            //    string text = await SQL.ReadSingleValueAsync($"SELECT Hinweis FROM {MainWindow.table}.misc WHERE id='1'");

            //    await Dispatcher.BeginInvoke(new Action(() => {
            //        if (lblHinweis.Text != text)
            //        {
            //            lblHinweis.Text = !string.IsNullOrWhiteSpace(text) ? text : "";

            //            if (!string.IsNullOrWhiteSpace(text))
            //                canvasHinweis.Visibility = Visibility.Visible;
            //            else canvasHinweis.Visibility = Visibility.Collapsed;
            //        } }));
            //}
        }


        private async Task 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 parkplatznr,  FROM {MainWindow.table}.`parkplaetze`", 0 , 1);
            var singlePark = await SQL.ReadDictionary2($"SELECT LPAD(p.parkplatznr, 2, '0'), 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);


            var allBe = await SQL.ReadDictionary2($"SELECT beNr,Parkplatz FROM {MainWindow.table}.beParkplaetze WHERE Parkplatz IS NOT NULL", 0, 1);
            //var allBe = await SQL.ReadSingleValueAsync($"SELECT beNr FROM {MainWindow.table}.beParkplaetze WHERE Parkplatz LIKE '%{nr},%'");

            await Dispatcher.BeginInvoke(new Action(() =>
            {
                var rects = BE.Children.OfType<Rectangle>();
                var tbs = BE.Children.OfType<TextBlock>().ToList();

                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);
                        var x = singlePark.TryGetValue(s.Name.TrimStart('P'), out string y);
                        var sp = tbs.First(p => p.Text == s.Name.TrimStart('P')).ToolTip as StackPanel;

                        if (singlePark.ContainsKey(s.Name.TrimStart('P')) && x && !string.IsNullOrWhiteSpace(y) && sp.Children[sp.Children.Count - 1].GetType() != typeof(TextBlock)) 
                            sp.Children.Add(new TextBlock() { Text = $"Ausgegeben an {y}" });
                    }
                    else if (!s.Name.StartsWith("Red"))
                    {
                        s.Fill = new SolidColorBrush(Colors.Green);
                    }

                }

                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);
                    }

                }

                foreach (Rectangle rect in Helper.FindVisualChildren<Rectangle>(BE).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 = "";

                        var match = allBe.FirstOrDefault(kvp => kvp.Value.Contains($"{nr},"));
                        if (!EqualityComparer<string>.Default.Equals(match.Key, default))
                        {
                            be = match.Key.ToString().PadLeft(2, '0');
                        }
                        //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 = BE.FindChildren<TextBlock>().Where(p => p.Text == nr.TrimStart('0')).First();
                            tb.ToolTip = sp;
                            tb.PreviewMouseLeftButtonDown -= ParkSetPreviewMouseLeftButtonDown;

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

                    }
                }



                lblGreenCounter.Text = rects.Where(p => p.Fill.ToString() == Brushes.Green.ToString()).Count().ToString();
                lblRedCounter.Text = rects.Where(p => p.Fill.ToString() == Brushes.Red.ToString() || p.Fill.ToString() == Brushes.Orange.ToString()).Count().ToString();
            }));
            //}
        }


        private async Task getMcFitCards()
        {
            var avail = await SQL.ReadSingleValueAsync($"SELECT 5-sum(AktuellAusgegeben) FROM {MainWindow.table}.mcFit");
            Dispatcher.Invoke(() => { lblmcfit.Text = lblmcfit2.Text = $"Aktuell verfügbare McFit Karten: {avail} von 5"; });
        }

        private async Task getFahrzeuge()
        {
            var res = await SQL.ReadListStringMultipleColumns($"SELECT * FROM {MainWindow.table}.fahrzeuge", 4);
            var i = res.First().Split(';');

            var bright = dark ? 100 : 50;

            var col = ColorHelper.ColorConverter.HsvToRgb(new HSV((100 / Delivery.GesamtFzg) * (Delivery.GesamtFzg - ((Convert.ToInt16(i[0]) * Delivery.LKW) + (Convert.ToInt16(i[1]) * Delivery.Sprinter) + (Convert.ToInt16(i[2]) * Delivery.PKW) + (Convert.ToInt16(i[3]) * Delivery.LKWLang))), 100, (byte)bright));

            Dispatcher.Invoke(() =>
            {
                lblLKW.Text = i[0];
                btnLKW.IsEnabled = i[0] == "0" ? false : true;

                lblSprinter.Text = i[1];
                btnSprinter.IsEnabled = i[1] == "0" ? false : true;

                lblPKW.Text = i[2];
                btnPKW.IsEnabled = i[2] == "0" ? false : true;

                lblLKWLang.Text = i[3];
                btnLKWLang.IsEnabled = i[3] == "0" ? false : true;

                lblLKW.Foreground = lblLKWLang.Foreground = lblSprinter.Foreground = lblPKW.Foreground = new SolidColorBrush(Color.FromRgb(col.R, col.G, col.B));
            });
        }

        private void getBikes()
        {
            var i = SQL.ReadSingleValue($"SELECT bikes FROM {MainWindow.table}.motorraeder");

            var bright = dark ? 100 : 50;
            var col = ColorHelper.ColorConverter.HsvToRgb(new HSV((100 / maxBikes) * (maxBikes - Convert.ToInt16(i)), 100, (byte)bright));

            Dispatcher.Invoke(() =>
            {
                lblBike.Text = $"{i} / {maxBikes}";
                lblBike.Foreground = new SolidColorBrush(Color.FromRgb(col.R, col.G, col.B));

                if (Convert.ToInt16(i) == maxBikes)
                {
                    btnBikeIn.IsEnabled = imgBikeIn.IsEnabled = false;
                    btnBikeIn.Background = new SolidColorBrush(Colors.Gray);
                    imgBikeIn.Opacity = 0.5;
                    btnBikeIn.ToolTip = imgBikeIn.ToolTip = "Keine Einfahrt mehr, da alle Kraftradparkplätze voll";
                }
                else
                {
                    btnBikeIn.IsEnabled = imgBikeIn.IsEnabled = true;
                    btnBikeIn.Background = new SolidColorBrush(Colors.PaleVioletRed);
                    imgBikeIn.Opacity = 1;
                    btnBikeIn.ToolTip = imgBikeIn.ToolTip = "Kraftrad fährt ein";
                }

                if (Convert.ToInt16(i) == 0)
                {
                    btnBikeOut.IsEnabled = imgBikeOut.IsEnabled = false;
                    btnBikeOut.Background = new SolidColorBrush(Colors.Gray);
                    imgBikeOut.Opacity = 0.5;
                    btnBikeOut.ToolTip = imgBikeOut.ToolTip = "Kein Kraftrad mehr im Werk";
                }
                else
                {
                    btnBikeOut.IsEnabled = imgBikeOut.IsEnabled = true;
                    btnBikeOut.Background = new SolidColorBrush(Colors.LightGreen);
                    imgBikeOut.Opacity = 1;
                    btnBikeOut.ToolTip = imgBikeOut.ToolTip = "Kraftrad fährt aus";
                }
            });
        }


        private void BtnManageUsers_Click(object sender, RoutedEventArgs e)
        {
            ManageUsers mU = new ManageUsers();
            mU.Owner = this;
            mU.ShowDialog();
        }

        private async void BtnCreateVisitor_Click(object sender, RoutedEventArgs e)
        {
            ManageVisitor mV = new ManageVisitor();
            mV.Owner = this;
            mV.ShowDialog();

            getToday();
        }

        private async void BtnCreateFirma_Click(object sender, RoutedEventArgs e)
        {
            CreateFirma cF = new CreateFirma();
            cF.Owner = this;
            cF.ShowDialog();

            getToday();
        }

        private void BtnManageAsp_Click(object sender, RoutedEventArgs e)
        {
            ManageAsp mA = new ManageAsp();
            mA.Owner = this;
            mA.ShowDialog();
        }


        private void btnFamily_Click(object sender, RoutedEventArgs e)
        {
            Family fam = new Family();
            fam.Owner = this;
            fam.ShowDialog();

            getToday();
        }


        private async void btnUserCreate_Click(object sender, RoutedEventArgs e)
        {
            CreateVisitor cV = new CreateVisitor();
            cV.Owner = this;
            cV.ShowDialog();

            getToday();
        }


        private void btnKarten_Click(object sender, RoutedEventArgs e)
        {
            Cards cards = new Cards();
            cards.Owner = this;
            cards.ShowDialog();
        }



        //private async void BtnNew_Click(object sender, RoutedEventArgs e)
        //{
        //    if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner)
        //    {
        //        reloadTimer.Stop();
        //        reloadTimerHinweis.Stop();

        //        if (dgToday.SelectedValue == null)
        //        {
        //            if (MessageBox.Show(this, "Möchten Sie wirklich eine Ankunft ohne vorherige Auswahl bestätigen?\n\nWenn die Firma/der Besucher in der Liste 'Ankunft heute' steht, bitte per Doppelklick auf die Zeile bestätigen", "Sicher?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
        //            {
        //                Arrivals arrivals = new Arrivals(this);
        //                arrivals.Owner = this;
        //                arrivals.Show();

        //                arrivals.Closed -= Arrivals_Closed;
        //                arrivals.Closed += Arrivals_Closed;
        //            }
        //        }
        //        else
        //        {
        //            Arrivals arrivals;
        //            //if (!(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Besucher:"))
        //            //    arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[0]);//(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().Replace("Besucher: ", ""));
        //            //else
        //            //    arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[17], 1);//(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().Replace("Besucher: ", ""));

        //            if ((dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Besucher:"))
        //                arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[17], 1);
        //            //(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().Replace("Besucher: ", ""));
        //            else if ((dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Führung:"))
        //                arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[17], 2, (dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString());
        //            else
        //                arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[0]);


        //            arrivals.Owner = this;
        //            arrivals.Show();

        //            arrivals.Closed -= Arrivals_Closed;
        //            arrivals.Closed += Arrivals_Closed;
        //        }

        //        //await getZutritte();
        //        //overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

        //        //dgOverview.Items.SortDescriptions.Clear();
        //        //dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
        //        //dgOverview.Items.Refresh();

        //    }
        //}

        private async void btnDelivery_Click(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).Tag.ToString() == "DB")
            {
                Delivery delivery = new Delivery(true);
                delivery.Owner = this;
                delivery.ShowDialog();

                await getZutritte();
            }
            else
            {
                Delivery delivery = new Delivery(false);
                delivery.Owner = this;
                delivery.Visibility = Visibility.Collapsed;
                delivery.ShowDialog();

                await getZutritte();
                await getFahrzeuge();
            }
            //overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

            //dgOverview.Items.SortDescriptions.Clear();
            //dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
            //dgOverview.Items.Refresh();
        }




        private async void Ausfahrt_Click(object sender, RoutedEventArgs e)
        {
            ContextMenu menu = new ContextMenu();
            menu.Width = 350;
            

            var result = await SQL.ReadListStringMultipleColumns($"SELECT arrivalTime, fzgType, firma, fahrer, kennzeichen FROM {MainWindow.table}.fzgTime WHERE fzgType = '{(sender as Button).Name.ToString().Replace("btn", "")}'", 5);

            foreach (var item in result)
            {
                var s = item.Split(';');
                var i = new MenuItem();
                i.Click += AusfahrMenu_Click;
                i.Header = $"Firma:\t\t\t{s[2]}\nFahrer:\t\t\t{s[3]}\nKennzeichen:\t\t{s[4]}\nEingefahren:\t\t{Convert.ToDateTime(s[0].ToString()).ToString("HH:mm  dd.MM.")}";
                i.Tag = s[1];
                menu.Items.Add(i);
            }

            (sender as Button).ContextMenu = menu;
            (sender as Button).ContextMenu.IsOpen = true;

        }

        private void AusfahrMenu_Click(object sender, RoutedEventArgs e)
        {
            FahrzeugAusfahrt((sender as MenuItem));
        }

        private void FahrzeugAusfahrt(MenuItem button)
        {
            int i = 0;
            string query = "";
            string fzgTime = "";

            var firma = button.Header.ToString().Split('\t');

            switch (button.Tag.ToString())
            {
                case "LKWLang":
                    //i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT lkwlang FROM {MainWindow.table}.fahrzeuge"));
                    fzgTime = ($"DELETE FROM {MainWindow.table}.fzgTime WHERE fzgType = 'LKWLang' AND firma = '{firma[3].Split('\n')[0]}' AND fahrer = '{firma[6].Split('\n')[0]}' AND kennzeichen = '{firma[8].Split('\n')[0]}'");

                    if (!string.IsNullOrWhiteSpace(fzgTime))
                        i = SQL.WriteSQLwithReturn(fzgTime).Result;

                    query = ($"UPDATE {MainWindow.table}.fahrzeuge SET lkwlang=lkwlang-{i}");
                    notifiedKennzeichen.Remove(firma[8].Split('\n')[0]);
                    break;
                case "LKW":
                    //i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT lkw FROM {MainWindow.table}.fahrzeuge"));
                    fzgTime = ($"DELETE FROM {MainWindow.table}.fzgTime WHERE fzgType = 'LKW' AND firma = '{firma[3].Split('\n')[0]}' AND fahrer = '{firma[6].Split('\n')[0]}' AND kennzeichen = '{firma[8].Split('\n')[0]}'");

                    if (!string.IsNullOrWhiteSpace(fzgTime))
                        i = SQL.WriteSQLwithReturn(fzgTime).Result;

                    query = ($"UPDATE {MainWindow.table}.fahrzeuge SET lkw=lkw-{i}");
                    notifiedKennzeichen.Remove(firma[8].Split('\n')[0]);
                    break;
                case "Sprinter":
                    //i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT sprinter FROM {MainWindow.table}.fahrzeuge"));
                    fzgTime = ($"DELETE FROM {MainWindow.table}.fzgTime WHERE fzgType = 'Sprinter' AND firma = '{firma[3].Split('\n')[0]}' AND fahrer = '{firma[6].Split('\n')[0]}' AND kennzeichen = '{firma[8].Split('\n')[0]}'");

                    if (!string.IsNullOrWhiteSpace(fzgTime))
                        i = SQL.WriteSQLwithReturn(fzgTime).Result;

                    query = ($"UPDATE {MainWindow.table}.fahrzeuge SET sprinter=sprinter-{i}");
                    notifiedKennzeichen.Remove(firma[8].Split('\n')[0]);
                    break;
                case "PKW":
                    //i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT pkw FROM {MainWindow.table}.fahrzeuge"));
                    fzgTime = ($"DELETE FROM {MainWindow.table}.fzgTime WHERE fzgType = 'PKW' AND firma = '{firma[3].Split('\n')[0]}' AND fahrer = '{firma[6].Split('\n')[0]}' AND kennzeichen = '{firma[8].Split('\n')[0]}'");

                    if (!string.IsNullOrWhiteSpace(fzgTime))
                      i = SQL.WriteSQLwithReturn(fzgTime).Result;

                    query = ($"UPDATE {MainWindow.table}.fahrzeuge SET pkw=pkw-{i}");
                    notifiedKennzeichen.Remove(firma[8].Split('\n')[0]);
                    break;
            }

            if (!string.IsNullOrWhiteSpace(query))
                SQL.WriteSQL(query);


            getFahrzeuge();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var x = (sender as TextBox).Text;
            var source = (dgToday.ItemsSource as DataView);
            if (!string.IsNullOrWhiteSpace(x))
            {
                var filter = ($"Name LIKE '%{x}%' OR Ansprechpartner_Intern LIKE '%{x}%' OR Verantwortlicher_MA_Firma LIKE '%{x}%'");
                source.RowFilter = filter;


                if (source.Count == 0)
                {
                    List<string> similarities = new List<string>();

                    foreach (var item in source.Table.Rows)
                    {
                        var ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[1].ToString().ToLower());
                        if (ratio > 60)
                            similarities.Add((item as DataRow).ItemArray[1].ToString());

                        ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[2].ToString().ToLower());
                        if (ratio > 60)
                            similarities.Add((item as DataRow).ItemArray[2].ToString());

                        ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[10].ToString().ToLower());
                        if (ratio > 60)
                            similarities.Add((item as DataRow).ItemArray[10].ToString());
                    }

                    StringBuilder str = new StringBuilder();
                    str.Append($"Name LIKE '%");

                    if (similarities.Count > 0)
                    {
                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Name LIKE '%");

                        str.Remove(str.Length - 16, 16);

                        str.Append(" OR Ansprechpartner_Intern LIKE '%");

                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Ansprechpartner_Intern LIKE '%");

                        str.Remove(str.Length - 34, 34);

                        str.Append(" OR Verantwortlicher_MA_Firma LIKE '%");

                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Verantwortlicher_MA_Firma LIKE '%");

                        str.Remove(str.Length - 37, 37);

                        source.RowFilter = str.ToString();
                    }
                    else
                    {
                        source.RowFilter = "";
                        //dgFirmen.DataContext = new DataTable();
                    }
                    //}

                }
            }
            else
            {
                source.RowFilter = "";
                //dgFirmen.DataContext = new DataTable();
            }
                //if (dgOverview != null) todayFirm.DefaultView.RowFilter = $"Name like '%{(sender as TextBox).Text}%' OR Ansprechpartner_Intern like '%{(sender as TextBox).Text}%' OR  Verantwortlicher_MA_Firma like '%{(sender as TextBox).Text}%'";

            //    if (string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearch.Visibility = Visibility.Visible;
            //if (!string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearch.Visibility = Visibility.Collapsed;
        }

        private void TbSearch_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //lblSearch.Visibility = Visibility.Collapsed;
        }

        private void TbSearch_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //if (string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearch.Visibility = Visibility.Visible;
        }



        private void tbSearchArrived_TextChanged(object sender, TextChangedEventArgs e)
        {
            var x = (sender as TextBox).Text;
            if (!string.IsNullOrWhiteSpace(x))
            {
                var filter = ($"Name LIKE '%{x}%' OR Kennzeichen LIKE '%{x}%' OR Ansprechpartner LIKE '%{x}%'");
                overv.DefaultView.RowFilter = filter;

                if (overv.DefaultView.Count == 0)
                {
                    List<string> similarities = new List<string>();

                    foreach (var item in overv.Rows)
                    {
                        var ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[2].ToString().ToLower());
                        if (ratio > 20)
                            similarities.Add((item as DataRow).ItemArray[2].ToString());

                        ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[11].ToString().ToLower());
                        if (ratio > 20)
                            similarities.Add((item as DataRow).ItemArray[11].ToString());

                        ratio = Fuzz.Ratio((sender as TextBox).Text.ToLower(), (item as DataRow).ItemArray[8].ToString().ToLower());
                        if (ratio > 20)
                            similarities.Add((item as DataRow).ItemArray[8].ToString());
                    }

                    StringBuilder str = new StringBuilder();
                    str.Append($"Name LIKE '%");

                    if (similarities.Count > 0)
                    {
                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Name LIKE '%");

                        str.Remove(str.Length - 16, 16);

                        str.Append(" OR Kennzeichen LIKE '%");

                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Kennzeichen LIKE '%");

                        str.Remove(str.Length - 23, 23);

                        str.Append(" OR Ansprechpartner LIKE '%");

                        foreach (var s in similarities)
                            str.Append($"{s}%' OR Ansprechpartner LIKE '%");

                        str.Remove(str.Length - 27, 27);

                        overv.DefaultView.RowFilter = str.ToString();
                    }
                }

                //if (dgOverview != null) overv.DefaultView.RowFilter = $"Name like '%{(sender as TextBox).Text}%' OR Kennzeichen like '%{(sender as TextBox).Text}%' OR Ansprechpartner like '%{(sender as TextBox).Text}%'";

                if (string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearchArrived.Visibility = Visibility.Visible;
                if (!string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearchArrived.Visibility = Visibility.Collapsed;
            }
            else
            {
                overv.DefaultView.RowFilter = "";
                //dgFirmen.DataContext = new DataTable();
            }
        }

        private void tbSearchArrived_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            lblSearchArrived.Visibility = Visibility.Collapsed;
        }

        private void tbSearchArrived_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace((sender as TextBox).Text)) lblSearchArrived.Visibility = Visibility.Visible;
        }


        private void btnClearSearch_Click(object sender, RoutedEventArgs e)
        {
            tbSearch.Text = "";
        }

        private void btnClearSearchArrived_Click(object sender, RoutedEventArgs e)
        {
            tbSearchArrived.Text = "";
        }








        private async void CBKleine_Unterweis_Click(object sender, RoutedEventArgs e)
        {
            CheckBox box = (sender as CheckBox);
            string id = ((box.DataContext) as DataRowView).Row.ItemArray[0].ToString();

            if (box.IsChecked == true)
            {
                if (((box.DataContext) as DataRowView).Row.ItemArray[1].ToString() == "1")
                {
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.firmen SET Kleine_Unterweisung_bis = '{(DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")}' WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.zutritte SET Kl_Unterweisung = 1 WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                }
                else if (((box.DataContext) as DataRowView).Row.ItemArray[1].ToString() == "2")
                {
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Kleine_Unterweisung_bis = '{(DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")}' WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.zutritte SET Kl_Unterweisung = 1 WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                }
            }
            else
            {
                if (((box.DataContext) as DataRowView).Row.ItemArray[1].ToString() == "1")
                {
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.firmen SET Kleine_Unterweisung_bis = '1901-01-01' WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.zutritte SET Kl_Unterweisung = 0 WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                }
                else if (((box.DataContext) as DataRowView).Row.ItemArray[1].ToString() == "2")
                {
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Kleine_Unterweisung_bis = '{(DateTime.Now.Date.AddYears(1)).ToString("yyyy-MM-dd")}' WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.zutritte SET Kl_Unterweisung = 0 WHERE Name = '{((box.DataContext) as DataRowView).Row.ItemArray[2]}'");
                }
            }
        }


        private async void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (LoggedInRole == Roles.Admin || LoggedInRole == Roles.Pförtner)
            {
                reloadTimer.Stop();
                reloadTimerHinweis.Stop();

                var dg = (sender as DataGridRow).TryFindParent<DataGrid>();

                if (string.IsNullOrWhiteSpace(dg.Name))
                {
                    Arrivals arrivals = new Arrivals(this);
                    arrivals.Owner = this;
                    arrivals.Show();

                    arrivals.Closed -= Arrivals_Closed;
                    arrivals.Closed += Arrivals_Closed;
                }
                else if (dg.Name == "dgToday")
                {
                    Arrivals arrivals;
                    //if ((dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Besucher:"))
                    //    arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[17], 1);
                    ////(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().Replace("Besucher: ", ""));
                    //else if ((dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Führung:"))
                    //    arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[22], 2, (dgToday.SelectedValue as DataRowView).Row.ItemArray[2].ToString());
                    //else

                    var res = -1;
                    int.TryParse((dgToday.SelectedValue as DataRowView).Row.ItemArray[0].ToString(), out res);

                    arrivals = new Arrivals(this, res);

                    arrivals.Owner = this;
                    
                    arrivals.Show();

                    arrivals.Closed -= Arrivals_Closed;
                    arrivals.Closed += Arrivals_Closed;
                }
                else if (dg.Name == "dgTodayBesucher")
                {
                    Arrivals arrivals = null;

                    if ((dgTodayBesucher.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Besucher:"))
                    {
                        var res = -1;
                        int.TryParse((dgTodayBesucher.SelectedValue as DataRowView).Row.ItemArray[0].ToString(), out res);
                        arrivals = new Arrivals(this, res, 1);
                    }
                    //(dgToday.SelectedValue as DataRowView).Row.ItemArray[1].ToString().Replace("Besucher: ", ""));
                    else if ((dgTodayBesucher.SelectedValue as DataRowView).Row.ItemArray[1].ToString().StartsWith("Führung:"))
                    {
                        var res = -1;
                        int.TryParse((dgTodayBesucher.SelectedValue as DataRowView).Row.ItemArray[0].ToString(), out res);
                        arrivals = new Arrivals(this, res, 2, (dgTodayBesucher.SelectedValue as DataRowView).Row.ItemArray[2].ToString());
                    }
                    //else
                    //    arrivals = new Arrivals(this, (int)(dgToday.SelectedValue as DataRowView).Row.ItemArray[0]);

                    if (arrivals != null)
                    {
                        arrivals.Owner = this;
                        arrivals.Show();

                        arrivals.Closed -= Arrivals_Closed;
                        arrivals.Closed += Arrivals_Closed;
                    }
                }
                else Log.WriteLog("Trying to open an Arrival with no DataGrid Name");

                //await getZutritte();
                //overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

                //dgOverview.Items.SortDescriptions.Clear();
                //dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
                //dgOverview.Items.Refresh();
                //


            }
        }

        private async void Arrivals_Closed(object sender, EventArgs e)
        {
            reloadTimer.Start();
            reloadTimerHinweis.Start();

            await getZutritte();
            await getPark();
        }

        private void BtnInfo_Click(object sender, RoutedEventArgs e)
        {
            var dc = ((sender as Button).DataContext) as DataRowView;
            int id = -1;
            string kat = "";

            if ((dc).Row.ItemArray[1].ToString().StartsWith("Führung:"))
            {
                kat = "3";
            }
            else if((dc).Row.ItemArray[1].ToString().StartsWith("Besucher:"))
            {
                id = (int)(dc).Row.ItemArray[0];
                kat = "2";
            }
            else
            {
                if ((dc).Row.ItemArray[7].ToString() != "")
                {
                    id = (int)(dc).Row.ItemArray[0];
                    kat = "1";
                }
            }

            AspInfo aI = new AspInfo(id, kat, 1);
            aI.Owner = this;
            aI.ShowDialog();
        }

        private void btnCard_Click(object sender, RoutedEventArgs e)
        {
            var dc = ((sender as Button).DataContext) as DataRowView;

            AddCardUser aI = new AddCardUser((dc).Row.ItemArray[2].ToString());
            aI.Owner = this;
            aI.ShowDialog();
        }

        private void btnKartenTausch_Click(object sender, RoutedEventArgs e)
        {
            KartenTausch kT = new KartenTausch();
            kT.Owner = this;
            kT.ShowDialog();
        }

        private void btnArrivalsOverview_Click(object sender, RoutedEventArgs e)
        {
            ArrivalsOverview aOv = new ArrivalsOverview(LoggedInRole);
            aOv.Owner = this;
            aOv.ShowDialog();
        }


        private void BtnInfoArrived_Click(object sender, RoutedEventArgs e)
        {
            var dc = ((sender as Button).DataContext) as DataRowView;
            int idFirma_Besucher = -1;
            string kat = "";

            if ((dc).Row.ItemArray[1].ToString() == "1")
            {
                idFirma_Besucher = (int)(dc).Row.ItemArray[14];
                kat = "1";
            }
            else if ((dc).Row.ItemArray[1].ToString() == "2")
            {
                idFirma_Besucher = (int)(dc).Row.ItemArray[14];
                kat = "2";
            }
#pragma warning disable CS0472
            if (idFirma_Besucher != null && idFirma_Besucher != -1)
            {
                AspInfo aI = new AspInfo(idFirma_Besucher, kat, 2, (dc).Row.ItemArray[0].ToString());
                aI.Owner = this;
                aI.ShowDialog();
            }
            else
                MessageBox.Show("Keine gültigen Informationen vorhanden", "Fehler", MessageBoxButton.OK, MessageBoxImage.Information);
        }
#pragma warning restore CS0472








        private async void Window_Closing(object sender, CancelEventArgs e)
        {
            if (Main.Visibility == Visibility.Visible)
            {
                if(gridSplitterVertical.Visibility == Visibility.Visible)
                {
                    // Aktuelle Column-Breiten speichern
                    Settings.WriteSetting("LeftColumn", gridToday.ColumnDefinitions[0].Width.Value);
                    Settings.WriteSetting("RightColumn", gridToday.ColumnDefinitions[2].Width.Value);
                }

                Settings.WriteSetting("WindowState", this.WindowState);

                Settings.Save();
                await SQL.WriteSQL($"UPDATE {MainWindow.table}.apptracker SET Online = 0 WHERE Username = '{Environment.UserName}'");
                //Properties.Settings.Default.Save();
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
#if DEBUG
            //if (e.Key == Key.LeftCtrl)
            //    BesucherCreateStart();

            //if(e.Key == Key.RightCtrl)
            //    Helper.SendMail("testTesttest");
#endif
        }

        private void TextBlock_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Helper.SendMail();
        }


        private void BtnHelp_Click(object sender, RoutedEventArgs e)
        {
            canvasHelp.Visibility = Visibility.Visible;
        }

        private void BtnCloseHelp_Click(object sender, RoutedEventArgs e)
        {
            canvasHelp.Visibility = Visibility.Collapsed;
        }


        private async void dgOverview_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var header = e.Column.Header;
            var newValue = (e.EditingElement as TextBox).Text;
            var id = (e.Row.Item as DataRowView).Row.ItemArray[0];


            switch (header)
            {
                case "Kennzeichen":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.zutritte SET Kennzeichen = '{newValue}' WHERE idzutritte = '{id}'");
                    break;
            }

            dgOverview.RowValidationErrorTemplate = new ControlTemplate();

            await getZutritte();
            //overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

            //dgOverview.Items.SortDescriptions.Clear();
            //dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
            //dgOverview.Items.Refresh();
        }



        private void btnDebug_Click(object sender, RoutedEventArgs e)
        {
            CheckVersion();
        }

        private void btnSignatures_Click(object sender, RoutedEventArgs e)
        {
            var iv = new ImageView(null, true);
            iv.Owner = this;
            iv.ShowDialog();
        }

        private async void btnCreateDeliveries_Click(object sender, RoutedEventArgs e)
        {
            var deliver = new ManageDeliveries();
            deliver.Owner = this;
            deliver.ShowDialog();

            await getZutritte();
            //overv = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -10 DAY", overv);

            //dgOverview.Items.SortDescriptions.Clear();
            //dgOverview.Items.SortDescriptions.Add(new SortDescription("Zutritt", ListSortDirection.Descending));
            //dgOverview.Items.Refresh();
        }


        private void btnResetLists_Click(object sender, RoutedEventArgs e)
        {
            gridBackground.RowDefinitions[1].Height = new GridLength(this.Height / 2);
            gridBackground.RowDefinitions[3].Height = new GridLength(1, GridUnitType.Star);
        }




        private void btnCreateParkausweis_Click(object sender, RoutedEventArgs e)
        {
            ParkausweisDisclaimer Pd = new ParkausweisDisclaimer();
            Pd.Owner = this;
            Pd.ShowDialog();
        }

        private void btnMcFitSignUp_Click(object sender, RoutedEventArgs e)
        {
            CreateMcFitUser cMFu = new CreateMcFitUser();
            cMFu.Owner = this;
            cMFu.ShowDialog();
        }

        private void btnCreateSpecialParkausweis_Click(object sender, RoutedEventArgs e)
        {
            CreateParkausweis cPa = new CreateParkausweis(true);
            cPa.Owner = this;
            cPa.ShowDialog();
        }

        private void btnGrantParkausweis_Click(object sender, RoutedEventArgs e)
        {
            GrantParkausweis gPa = new GrantParkausweis();
            gPa.Owner = this;
            gPa.ShowDialog();
        }

        private void btnListParkausweis_Click(object sender, RoutedEventArgs e)
        {
            ManageParkausweis mPa = new ManageParkausweis();
            mPa.Owner = this;
            mPa.ShowDialog();
        }

        private void btnCheckParkausweis_Click(object sender, RoutedEventArgs e)
        {
            CheckParkausweis checkPa = new CheckParkausweis();
            checkPa.Owner = this;
            checkPa.ShowDialog();
        }

        private void btnPrintParkausweis_Click(object sender, RoutedEventArgs e)
        {
            PrintParkausweis pPa = new PrintParkausweis();
            pPa.Owner = this;
            pPa.Show();
        }


        private void btnSetHinweis_Click(object sender, RoutedEventArgs e)
        {
            SetHinweis sHw = new SetHinweis();
            sHw.Owner = this;
            sHw.ShowDialog();

            getHinweis();
        }


        private void btnCheckKennzeichen_Click(object sender, RoutedEventArgs e)
        {
            CheckKennzeichen cKz = new CheckKennzeichen();
            cKz.Owner = this;
            cKz.Show();
        }


        private void btnBelegung_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            Belegung be = new Belegung();
            be.Owner = this;
            be.ShowDialog();

            getPark();

            this.Cursor = Cursors.Arrow;
        }

        private void btnBEImages_Click(object sender, RoutedEventArgs e)
        {
            BEImage beI = new BEImage();
            beI.Owner = this;
            beI.Show();
        }

        private void btnNotifications_Click(object sender, RoutedEventArgs e)
        {
            Notifications nTf = new Notifications();
            nTf.Owner = this;
            nTf.ShowDialog();
        }

        private void btnApproveFzg_Click(object sender, RoutedEventArgs e)
        {
            ApproveFzg fzg = new ApproveFzg();
            fzg.Owner = this;
            fzg.Show();
        }




        private async void ShowToast(DataTable dt)
        {
            try
            {
                bool isAdminEntry = false;
                if (LoggedInRole == Roles.Admin)
                {
                    var vertAspName = SQL.ReadSingleValue($"SELECT Vertreter FROM {MainWindow.table}.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");
                    var nameAspVert = SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");

                    var check = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.zutritte where Zutritt >= now() + INTERVAL -20 SECOND AND (idFirma_Besucher IN (select idfirmen from {MainWindow.table}.firmen where Ersteller = '{Environment.UserName}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                         $"OR Ersteller = '{vertAspName}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                         $"OR Ersteller = '{nameAspVert}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                         $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}') " +
                         $"OR idFirma_Besucher IN (select idbesucher from {MainWindow.table}.besucher where Ersteller = '{Environment.UserName}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                         $"OR Ersteller = '{vertAspName}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
                         $"OR Ersteller = '{nameAspVert}' " +
                         $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
                         $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'))");

                    isAdminEntry = check.Rows.Count > 0;
                }

                if (LoggedInRole != Roles.Pförtner)
                {
                    //1 = Firma
                    if (dt.Rows.Count > 0)
                    {
                        if (int.Parse(dt.Rows[0].ItemArray[1].ToString()) == 1)
                        {
                            if (dt.Rows[0].ItemArray[14] != DBNull.Value)
                            {
                                if ((LoggedInRole == Roles.Admin && isAdminEntry) || (LoggedInRole != Roles.Admin))
                                {
                                    var idFirmaBesucher = dt.Rows[0].ItemArray[14];

                                    var firma = dt.Rows[0].ItemArray[2];
                                    var name = dt.Rows[0].ItemArray[8].ToString().Split('/')[0];
                                    var anzPers = dt.Rows[0].ItemArray[6].ToString();

                                    var begleit = int.Parse(anzPers) == 1 ? "Begleitperson" : "Begleitpersonen";

                                    new ToastContentBuilder()
                                        .AddAppLogoOverride(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png"), ToastGenericAppLogoCrop.Circle)
                                        .AddText($"Firma {firma}")
                                        .AddText($"{name} ist mit")
                                        .AddText($"{anzPers} {begleit} angekommen")
                                        .SetToastDuration(ToastDuration.Long)
                                        .Show(t => t.ExpirationTime = DateTime.Now.AddHours(2));
                                }
                            }
                        }// 2 = Besucher
                        else if (int.Parse(dt.Rows[0].ItemArray[1].ToString()) == 2)
                        {
                            if (dt.Rows[0].ItemArray[14] != DBNull.Value)
                            {
                                if ((LoggedInRole == Roles.Admin && isAdminEntry) || (LoggedInRole != Roles.Admin))
                                {
                                    var firma = dt.Rows[0].ItemArray[2];
                                    var name = dt.Rows[0].ItemArray[8].ToString().Split('/')[0];
                                    var anzPers = dt.Rows[0].ItemArray[6].ToString();

                                    var begleit = int.Parse(anzPers) == 1 ? "Begleitperson" : "Begleitpersonen";

                                    new ToastContentBuilder()
                                        .AddAppLogoOverride(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png"), ToastGenericAppLogoCrop.Circle)
                                        .AddText($"Besucher {name}")
                                        .AddText($"mit {anzPers} {begleit}")
                                        .AddText($"angekommen")
                                        .SetToastDuration(ToastDuration.Long)
                                        .Show(t => t.ExpirationTime = DateTime.Now.AddHours(2));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.Message);
            }
        }


        public void CenterWindowOnScreen(Window window)
        {
            double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
            double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
            double windowWidth = window.Width;
            double windowHeight = window.Height;
            window.Left = (screenWidth / 2) - (windowWidth / 2);
            window.Top = (screenHeight / 2) - (windowHeight / 2);
        }

        private async void Window_ContentRendered(object sender, EventArgs e)
        {

        }

        private async void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            QueryParkEmailUsers();
            QueryFzgAnmeldungEmailUsers();

            canvasSettings.Visibility = Visibility.Visible;

            cbShowParkcardToAccept.IsChecked = Settings.GetSettingBool("ShowParkcardAccept");
            cbShowParkcardToPrint.IsChecked = Settings.GetSettingBool("ShowParkcardPrint");
            //cbShowParkcardToAccept.IsChecked = Properties.Settings.Default.ShowParkcardAccept;
            //cbShowParkcardToPrint.IsChecked = Properties.Settings.Default.ShowParkcardPrint;
        }

        private void cbShowParkcardToAccept_Checked(object sender, RoutedEventArgs e)
        {
            Settings.WriteSetting("ShowParkcardAccept", true);
            //Properties.Settings.Default.ShowParkcardAccept = true;
        }

        private void cbShowParkcardToAccept_Unchecked(object sender, RoutedEventArgs e)
        {
            Settings.WriteSetting("ShowParkcardAccept", false);
            //Properties.Settings.Default.ShowParkcardAccept = false;
        }

        private void cbShowParkcardToPrint_Checked(object sender, RoutedEventArgs e)
        {
            Settings.WriteSetting("ShowParkcardPrint", true);
            //Properties.Settings.Default.ShowParkcardPrint = true;
        }

        private void cbShowParkcardToPrint_Unchecked(object sender, RoutedEventArgs e)
        {
            Settings.WriteSetting("ShowParkcardPrint", false);
            //Properties.Settings.Default.ShowParkcardPrint = false;
        }


        private void btnAddParkEmailUser_Click(object sender, RoutedEventArgs e)
        {
            tbParkEmailUserEmail.Text = "@deutschebahn.com";

            cm.IsOpen = true;
            tbParkEmailUserEmail.Focus();
        }

        private async void btnDelParkEmailUser_Click(object sender, RoutedEventArgs e)
        {
            if (dgParkEmailUsers.SelectedIndex != -1)
            {
                int id = (int)(dgParkEmailUsers.SelectedItem as DataRowView).Row.ItemArray[0];

                var name = SQL.ReadSingleValue($"SELECT Name FROM {MainWindow.table}.parkEmailUsers WHERE idparkEmailUsers = {id}");

                if (MessageBox.Show($"Möchten Sie den Empfänger {name} wirklich löschen?", "Sicher löschen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.parkEmailUsers WHERE idparkEmailUsers = {id}");

                    QueryParkEmailUsers();
                }
            }
        }



        private void btnAddFzgAnmeldungUser_Click(object sender, RoutedEventArgs e)
        {
            tbFzgAnmeldungUserEmail.Text = "@deutschebahn.com";

            popFzgAnmeldung.IsOpen = true;
            tbFzgAnmeldungUserEmail.Focus();
        }

        private async void btnDelFzgAnmeldungUser_Click(object sender, RoutedEventArgs e)
        {
            if (dgFzgAnmeldungUsers.SelectedIndex != -1)
            {
                int id = (int)(dgFzgAnmeldungUsers.SelectedItem as DataRowView).Row.ItemArray[0];

                if (MessageBox.Show($"Möchten Sie den Empfänger {(dgFzgAnmeldungUsers.SelectedItem as DataRowView).Row.ItemArray[1]} wirklich löschen?", "Sicher löschen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    var command = new MySqlCommand($"DELETE FROM {MainWindow.table}.fzgAnmeldungEmail WHERE idfzgAnmeldungEmail = @id");
                    command.Parameters.Add(new MySqlParameter("id", id));
                    await SQL.WriteSQL(command);


                    QueryFzgAnmeldungEmailUsers();
                }
            }
        }

        private async Task QueryFzgAnmeldungEmailUsers()
        {
            FzgAnmeldungEmailUsers = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.fzgAnmeldungEmail");
            dgFzgAnmeldungUsers.ItemsSource = FzgAnmeldungEmailUsers.DefaultView;
        }

        private void AddFzgAnmeldungEmailUserTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                AddFzgAnmeldungEmailUser();
                popFzgAnmeldung.IsOpen = false;
            }
        }
        private void AddFzgAnmeldungEmailUserAdd_Click(object sender, RoutedEventArgs e)
        {
            AddFzgAnmeldungEmailUser();
            popFzgAnmeldung.IsOpen = false;
        }

        private async void AddFzgAnmeldungEmailUser()
        {
            if (!string.IsNullOrWhiteSpace(tbFzgAnmeldungUserEmail.Text))
            {
                string name = Helper.GetNameFromMail(tbFzgAnmeldungUserEmail.Text);
                if (name == "-1") return;

                var command = new MySqlCommand($"INSERT INTO {MainWindow.table}.fzgAnmeldungEmail (Email, Name, ModifiedBy, ModifiedAt) VALUES (@pEmail, @pName, @pModifiedBy, @pModifiedAt)");
                command.Parameters.Add(new MySqlParameter("pName", name));
                command.Parameters.Add(new MySqlParameter("pEmail", tbFzgAnmeldungUserEmail.Text));
                command.Parameters.Add(new MySqlParameter("pModifiedBy", Environment.UserName));
                command.Parameters.Add(new MySqlParameter("pModifiedAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                await SQL.WriteSQL(command);

                QueryFzgAnmeldungEmailUsers();
            }
        }


        private async Task QueryParkEmailUsers()
        {
            ParkEmailUsers = await SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.parkEmailUsers");
            dgParkEmailUsers.ItemsSource = ParkEmailUsers.DefaultView;
        }

        private void AddParkEmailUserTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                AddParkEmailUser();
                cm.IsOpen = false;
            }
        }
        private void AddParkEmailUserAdd_Click(object sender, RoutedEventArgs e)
        {
            AddParkEmailUser();
            cm.IsOpen = false;
        }

        private async void AddParkEmailUser()
        {
            if (!string.IsNullOrWhiteSpace(tbParkEmailUserEmail.Text))
            {
                string name = Helper.GetNameFromMail(tbParkEmailUserEmail.Text);
                if (name == "-1") return;

                var command = new MySqlCommand($"INSERT INTO {MainWindow.table}.parkEmailUsers (Name, Email, ModifiedBy) VALUES (@pName, @pEmail, @pModifiedBy)");
                command.Parameters.Add(new MySqlParameter("pName", name));
                command.Parameters.Add(new MySqlParameter("pEmail", tbParkEmailUserEmail.Text));
                command.Parameters.Add(new MySqlParameter("pModifiedBy", Helper.InsertSpaceBeforeUpperCase(Environment.UserName)));

                await SQL.WriteSQL(command);

                QueryParkEmailUsers();
            }
        }


        private void btnCloseSettings_Click(object sender, RoutedEventArgs e)
        {
            canvasSettings.Visibility = Visibility.Collapsed;
            Settings.Save();
            //Properties.Settings.Default.Save();
        }



        private void gridSplitter_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            GridSplitter splitter = sender as GridSplitter;
            Window window = Window.GetWindow(splitter);

            splitter.UpdateLayout();

            Point splitterPosition = splitter.TransformToAncestor(window).Transform(new Point(0, 0));

            if (splitterPosition.Y > (this.ActualHeight - 190))
            {
                e.Handled = true; // Bewegung stoppen
                gridRowTop.Height = new GridLength(this.ActualHeight - 160 - 190);
            }
        }


        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {

            //if(e.NewSize.Height > e.PreviousSize.Height)

            var height = new GridLength(gridBackground.RowDefinitions[1].Height.Value + (e.NewSize.Height - e.PreviousSize.Height));

            if (height.Value > 0)
                gridBackground.RowDefinitions[1].Height = height;
            //else
            //    gridBackground.RowDefinitions[1].Height = new GridLength(gridBackground.RowDefinitions[1].Height.Value + (e.PreviousSize.Height - e.NewSize.Height));

            System.Diagnostics.Debug.WriteLine("WindowSize: " + this.Width );

            if (this.WindowState == WindowState.Normal && ReadyToSavePosition)
            {
                Settings.WriteSetting("Width", this.Width);
                Settings.WriteSetting("Height", this.Height);
            }



            //double maxheight = this.ActualHeight - 120 - 195;
            //double actualheight = this.ActualHeight - 120 - gridBackground.RowDefinitions[1].Height.Value;
            //if (actualheight <= 195)
            //{
            //    gridBackground.RowDefinitions[1].Height = new GridLength(maxheight);
            //    return;
            //}

            //Helper.CheckScale(this);
        }

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

            if (ReadyToSavePosition)
            {
                Settings.WriteSetting("Top", this.Top);
                Settings.WriteSetting("Left", this.Left);
            }
            //Helper.CheckScale(this);
        }

        private void btnIvoBackground_Click(object sender, RoutedEventArgs e)
        {
            canvasIvo.Visibility = canvasIvo.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        }

        private void ParkPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string index = "-1";

            index = (sender as TextBlock).Tag.ToString();


            BEImage beI = new BEImage(Convert.ToInt32(index));
            beI.Owner = this;
            beI.Show();
        }

        private async void ParkSetPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (LoggedInRole == Roles.Pförtner || LoggedInRole == Roles.Admin)
            {
                var parkplatz = (sender as TextBlock).Text;

                if ((parkplatz == "7" && BE.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" && BE.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" && BE.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 BE.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);
                        }
                        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) VALUES (@pParkplatz)");
                            command.Parameters.Add(new MySqlParameter("pParkplatz", parkplatz));
                            await SQL.WriteSQL(command);
                        }
                    }
                }


                var rects = BE.Children.OfType<Rectangle>();
                lblGreenCounter.Text = rects.Where(p => p.Fill.ToString() == Brushes.Green.ToString()).Count().ToString();
                lblRedCounter.Text = rects.Where(p => p.Fill.ToString() == Brushes.Red.ToString()).Count().ToString();
            }
        }

        private async void G_ParkPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var parkplatz = (sender as TextBlock).Text;

            foreach (var rect in BesuchP.Children.OfType<Grid>().First().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}'");
                    }
                    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 (@parkplatz, @ausgegeben)", new List<MySqlParameter>()
                                                    {
                                                        new MySqlParameter("@parkplatz", $"G{parkplatz}"),
                                                        new MySqlParameter("@ausgegeben", Helper.InsertSpaceBeforeUpperCase(Environment.UserName))
                                                    });
                    }
                }
            }
        }

        private async void BikeEinfahrt_Click(object sender, RoutedEventArgs e)
        {
            var i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT bikes FROM {MainWindow.table}.motorraeder"));

            if (i >= maxBikes)
                MessageBox.Show("Keine freien Motorradparkplätze\n\nEinfahrt verweigert!", "Kein Platz", MessageBoxButton.OK, MessageBoxImage.Error);
            else if (i < 0)
            {
                MessageBox.Show("Es ist ein Fehler aufgetreten", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                Log.WriteLog("Motorrad Einfahrt < 0");
            }
            else
            {
                await SQL.WriteSQL($"UPDATE {MainWindow.table}.motorraeder SET bikes={i + 1}");
            }

            getBikes();
        }

        private async void BikeAusfahrt_Click(object sender, RoutedEventArgs e)
        {
            var i = Convert.ToInt16(SQL.ReadSingleValue($"SELECT bikes FROM {MainWindow.table}.motorraeder"));

            if (i <= 0)
            {
                MessageBox.Show("Kein Motorrad mehr im Werk", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                Log.WriteLog("Motorrad Ausfahrt < 0");
            }
            else
            {
                await SQL.WriteSQL($"UPDATE {MainWindow.table}.motorraeder SET bikes={i - 1}");
            }

            getBikes();
        }




        private void btnDarkMode_Click(object sender, RoutedEventArgs e)
        {
            ChangeTheme();
        }


        private void AccentMenuItem_Click(object sender, RoutedEventArgs e)
        {
            string Color = "Blue";

            switch((sender as MenuItem).Header)
            {
                case "Blau":
                    Color = "Blue";
                    break;
                case "Braun":
                    Color = "Brown";
                    break;
                case "Grün":
                    Color = "Green";
                    break;
                case "Magenta":
                    Color = "Magenta";
                    break;
                case "Orange":
                    Color = "Orange";
                    break;
                case "Rot":
                    Color = "Red";
                    break;
                case "Grau":
                    Color = "Steel";
                    break;
                case "Gelb":
                    Color = "Yellow";
                    break;
            }

            ChangeAccent(Color);
            Settings.WriteSetting("Accent", Color);
            //Properties.Settings.Default.Accent = Color;
        }

        bool dark = false;
        private void ChangeTheme()
        {
            if (!dark)
            {
                ControlzEx.Theming.ThemeManager.Current.ChangeTheme(Application.Current, "Dark.Blue");
                imgDarkModeButton.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sun.png", UriKind.Absolute));

                imgLKWLang.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKWLang_dark.png", UriKind.Absolute));
                imgLKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKW_dark.png", UriKind.Absolute));
                imgSprinter.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sprinter_dark.png", UriKind.Absolute));
                imgPKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/PKW_dark.png", UriKind.Absolute));
                imgBike.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Bike_dark.png", UriKind.Absolute));

                dark = true;
                Settings.WriteSetting("DarkMode", true);
                //Properties.Settings.Default.DarkMode = true;
            }
            else
            {
                ControlzEx.Theming.ThemeManager.Current.ChangeTheme(Application.Current, "Light.Blue");
                imgDarkModeButton.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                    + ";component/"
                    + $"Resources/Moon.png", UriKind.Absolute));

                imgLKWLang.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKWLang.png", UriKind.Absolute));
                imgLKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKW.png", UriKind.Absolute));
                imgSprinter.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sprinter.png", UriKind.Absolute));
                imgPKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/PKW.png", UriKind.Absolute));
                imgBike.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Bike.png", UriKind.Absolute));


                dark = false;
                Settings.WriteSetting("DarkMode", false);
                //Properties.Settings.Default.DarkMode = false;
            }

            getFahrzeuge();
            getBikes();
        }

        private void ChangeTheme(bool darkSet)
        {
            if (darkSet)
            {
                ControlzEx.Theming.ThemeManager.Current.ChangeTheme(Application.Current, "Dark.Blue");
                imgDarkModeButton.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sun.png", UriKind.Absolute));


                imgLKWLang.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKWLang_dark.png", UriKind.Absolute));
                imgLKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKW_dark.png", UriKind.Absolute));
                imgSprinter.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sprinter_dark.png", UriKind.Absolute));
                imgPKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/PKW_dark.png", UriKind.Absolute));
                imgBike.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Bike_dark.png", UriKind.Absolute));


                dark = true;
                Settings.WriteSetting("DarkMode", true);
                //Properties.Settings.Default.DarkMode = true;
            }
            else
            {
                ControlzEx.Theming.ThemeManager.Current.ChangeTheme(Application.Current, "Light.Blue");
                imgDarkModeButton.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                    + ";component/"
                    + $"Resources/Moon.png", UriKind.Absolute));

                imgLKWLang.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKWLang.png", UriKind.Absolute));
                imgLKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/LKW.png", UriKind.Absolute));
                imgSprinter.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Sprinter.png", UriKind.Absolute));
                imgPKW.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/PKW.png", UriKind.Absolute));
                imgBike.Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                    + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                    + ";component/"
                                    + $"Resources/Bike.png", UriKind.Absolute));

                dark = false;
                Settings.WriteSetting("DarkMode", false);
                //Properties.Settings.Default.DarkMode = false;
            }

            getFahrzeuge();
            getBikes();
        }

        private void ChangeAccent(string Color)
        {
            Color = Color == null || Color == "" ? "Blue" : Color;
            string DarkLight = Settings.GetSettingBool("DarkMode") ? "Dark" : "Light";

            ControlzEx.Theming.ThemeManager.Current.ChangeTheme(Application.Current, $"{DarkLight}.{Color}");
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabSonstiges.IsSelected)
                lblmcfit.Visibility = Visibility.Visible;
            else
                lblmcfit.Visibility = Visibility.Collapsed;

            if (tabPfoertner.IsSelected)
            {
                if (Helper.GetCOMPortCount() > 1)
                    btnCOMSelector.Visibility = Visibility.Visible;
                else if (Helper.GetCOMPortCount() == 1)
                    Settings.WriteSetting("COMPort", Regex.Match(Helper.GetCOMPorts().First(), @"COM\d+(?=\))").Value);

                if (Helper.GetCOMPortCount() == 0)
                    return;

                Helper.InitSerial();
            }
        }

        private void imgLoading_AnimationCompleted(DependencyObject d, XamlAnimatedGif.AnimationCompletedEventArgs e)
        {
            var gif = XamlAnimatedGif.AnimationBehavior.GetAnimator(imgLoading);
            gif.Dispose();

            gridSpinner.Visibility = Visibility.Collapsed;
        }

        private void MetroWindow_DragLeave(object sender, DragEventArgs e)
        {
            Helper.CheckScale(this);
        }

        private void MetroWindow_StateChanged(object sender, EventArgs e)
        {
            Helper.CheckScale(this);
        }

        private void MetroWindow_DpiChanged(object sender, DpiChangedEventArgs e)
        {
            Helper.CheckScale(this);
        }

        private void btnCOMSelector_Click(object sender, RoutedEventArgs e)
        {
            COMSelector cOMSelector = new COMSelector();
            cOMSelector.ShowDialog();
        }

        private void btnCheckAusgegebeneParkausweise_Click(object sender, RoutedEventArgs e)
        {
            AusgegebeneParkausweise aPw = new AusgegebeneParkausweise();
            aPw.ShowDialog();
        }

        private void btnEnstoerdienste_Click(object sender, RoutedEventArgs e)
        {
            ManageEntstoerdienste mEd = new ManageEntstoerdienste();
            mEd.ShowDialog();
        }

    }


    public class ReturnToolTip : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if(MainWindow.LoggedInRole == Roles.Admin || MainWindow.LoggedInRole == Roles.Pförtner)
            {
                return "Doppelklick um Ankunft zu Bestätigen";
            }
            else
            {
                return "Von Ihnen eingegebene Firmen/Besucher, die für heute angemeldet sind";
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


    public class Overview
    {
        public string Kategorie;
        public string Name;
        public string Zutritt;
        public string Pruefung_Zutritt;
        public string Pruefung_Einweisung;
        public int Kl_Unterweisung;
        public string Kennzeichen;
        public string Bemerkung;
    }

    public enum Roles
    {
        Pförtner,
        FFK,
        Admin,
        FFK_Sasse,
        M2,
        Organisator,
        M2_AM,
        None
    }
}
