using ControlzEx.Standard;
using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Asn1.Crmf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für Belegung.xaml
    /// </summary>
    public partial class Belegung : 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));
        }

        ObservableCollection<ComboBoxItem> list = new ObservableCollection<ComboBoxItem>();
        DataTable be = new DataTable("be");
        DataTable firm = new DataTable("firm");
        string lastAddedId = "0";

        DispatcherTimer timer = new DispatcherTimer();




        public Belegung()
        {
            this.DataContext = this;

            InitializeComponent();

            FillBEList();

            cbBE.ItemsSource = list;
            //var pl = SQL.ReadListString($"SELECT Username FROM {MainWindow.table}.users WHERE Role = 1").Result;
            //pl.ForEach(p => Helper.InsertSpaceBeforeUpperCase(p));
            //cbPL.ItemsSource = pl;


            be = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.beBelegung WHERE bis >= curdate() ORDER BY beNr ASC, bis ASC").Result;
            dgBelegung.DataContext = be;
            
            FillFirmen();


            //.AsEnumerable()
            //                    .Select(row => row["Name"].ToString() + "\t" + row["Beauftragte_Leistung"].ToString())
            //                    .ToList();

            timer.Tick += timer_Tick;
            timer.Interval = TimeSpan.FromMilliseconds(200);
        }

        private void FillFirmen()
        {
            firm = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.firmen WHERE Arbeitsende >= curdate() ORDER BY Name ASC ").Result; //+
                                                                                                                                     //$"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(" ", "")}' " +


            var items = (from DataRow row in firm.Rows
                         select new BEFirma
                         {
                             idFirmen = row["idFirmen"].ToString(),
                             Name = row["Name"].ToString(),
                             Beauftragte_Leistung = row["Beauftragte_Leistung"].ToString()
                         })
                        .Concat(new[] {
                            new BEFirma
                            {
                                Name = "--- Neue Firma hinzufügen ---"
                            }
                        });                                                                                                           //$"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)}') ORDER BY Name ASC").Result;


            cbFirma.ItemsSource = items;
        }



        // The timer's Tick event.
        private bool BlinkOn = false;
        int blinkCount = 0;
        int index = -1;
        private void timer_Tick(object sender, EventArgs e)
        {
            if (blinkCount == 0) {
                var row = be.Select($"idbeBelegung = {lastAddedId}").FirstOrDefault();
                DataRowView rowView = be.DefaultView.Cast<DataRowView>().FirstOrDefault(drv => drv.Row == row);
                index = dgBelegung.Items.IndexOf(rowView);
            }

            blinkCount++;
            if (BlinkOn)
            {
                dgBelegung.SelectedIndex = index;
            }
            else
            {
                dgBelegung.SelectedIndex = -1;
            }
            BlinkOn = !BlinkOn;

            if (blinkCount > 11)
            {
                timer.Stop();
                blinkCount = 0;
            }
        }

        private void FillBEList()
        {
            List<string> BEs = new List<string>();
            var numbers = Helper.GetBENumbers();
            var desc = Helper.GetBEDescription();
            var files = Helper.GetBEFileNames();

            list.Add(new ComboBoxItem());

            for (int i = 0; i < numbers.Count; i++)
            {
                var cbi = new ComboBoxItem()
                {
                    Content = $"BE-Fläche {numbers[i]} ({desc[i]})",
                    ToolTip = new Image()
                    {
                        Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                        + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                        + ";component/"
                                        + files[i], UriKind.Absolute)),
                        MaxWidth = 900,
                        MaxHeight = 400
                    }
                };

                ToolTipService.SetInitialShowDelay(cbi, 0);
                ToolTipService.SetHorizontalOffset(cbi, 250);

                list.Add(cbi);
            }
        }


        private void DataGrid_Filled()
        {
            if (cbBE.SelectedIndex != 0 && cbBE.SelectedIndex != -1)
                lblBE.Text = $"Aktuelle Buchungen für {(cbBE.SelectedItem as ComboBoxItem).Content.ToString()}:";
            else lblBE.Text = "Alle aktuell gebuchten BE-Flächen:";


            var ldps = Helper.FindVisualChildren<DatePicker>(dgBelegung);

            if (cbBE.SelectedIndex == 0 || cbBE.SelectedIndex == -1)
            {
                foreach (var d in ldps)
                    d.IsEnabled = false;

                var bem = Helper.FindVisualChildren<System.Windows.Controls.TextBox>(dgBelegung).Where(p => p.Template.TargetType.FullName == "System.Windows.Controls.TextBox");
                
                foreach(var b in  bem)
                    b.IsEnabled = false;
            }

            foreach (var row in dgBelegung.Items)
            {
                try
                {
                    var files = Helper.GetBEFileNames();
                    var tb = dgBelegung.Columns[0].GetCellContent(row);
                    //DataGridCell cell = dgBelegung.Columns[0].GetCellContent(row).Parent as DataGridCell;
                    var file = files.Where(p => p.Contains((row as DataRowView).Row.ItemArray[1].ToString())).First(); // files[Convert.ToInt16((row as DataRowView).Row.ItemArray[1]) - 1];

                    if (tb != null)
                    {
                        tb.ToolTip = new Image()
                        {
                            Source = new BitmapImage(new Uri(@"pack://application:,,,/"
                                            + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
                                            + ";component/"
                                            + file, UriKind.Absolute)),
                            MaxWidth = 900,
                            MaxHeight = 400
                        };

                        ToolTipService.SetHorizontalOffset(tb, this.Width);
                    }
                }
                catch (Exception)
                {

                }
            }
        }

        private async void cbBE_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if((sender as ComboBox).SelectedIndex > 0)
                dpVon.IsEnabled = dpBis.IsEnabled = tbBemerkung.IsEnabled = cbFirma.IsEnabled = true;
            else dpVon.IsEnabled = dpBis.IsEnabled = tbBemerkung.IsEnabled = cbFirma.IsEnabled = false;

            QueryBelegung();
        }

        private async void BlackoutDates()
        {
            List<string> blocked = new List<string>();
            dpVon.BlackoutDates.Clear();
            dpBis.BlackoutDates.Clear();

            if (cbBE.SelectedIndex > 0)
            {
                var numbers = Helper.GetBENumbers();
                var beNR = cbBE.SelectedIndex == 0 ? "0" : numbers[cbBE.SelectedIndex - 1];
                blocked = await SQL.ReadListStringMultipleColumns($"SELECT idbeBelegung, von, bis FROM {MainWindow.table}.beBelegung WHERE beNr = {beNR}");/*,3,";",";",";",";",0,4,5*/


                var ldps = Helper.FindVisualChildren<DatePicker>(dgBelegung).ToList();
                foreach (var d in ldps) d.BlackoutDates.Clear();


                foreach (var b in blocked)
                {
                    var blackout = new CalendarDateRange();
                    blackout.Start = DateTime.Parse(b.Split(';')[1]);
                    blackout.End = DateTime.Parse(b.Split(';')[2]);

                    if (!dpVon.BlackoutDates.Contains(blackout)) dpVon.BlackoutDates.Add(blackout);
                    if (!dpBis.BlackoutDates.Contains(blackout)) dpBis.BlackoutDates.Add(blackout);

                    foreach (var d in ldps)
                    {
                        //Selected Date CANNOT be a BlackoutDate
                        if (!d.BlackoutDates.Contains(blackout))
                            if (d.SelectedDate != null && !(d.SelectedDate.Value >= blackout.Start && d.SelectedDate.Value <= blackout.End))
                            {
                                //Debug.WriteLine($"{d.Name}  {d.SelectedDate.Value} >= {blackout.Start} && {d.SelectedDate.Value} <= {blackout.End}    {(d.SelectedDate.Value >= blackout.Start && d.SelectedDate.Value <= blackout.End)}");
                                d.BlackoutDates.Add(blackout);
                            }
                    }
                }
            }
        }

        private async void btnBookBE_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbBE.SelectedIndex == 0 || cbBE.SelectedIndex == -1)
                    MessageBox.Show("BE-Fläche muss ausgewählt sein", "Fehlende Angabe", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (!dpVon.SelectedDate.HasValue)
                    MessageBox.Show("Start der Buchung muss korrekt gewählt sein", "Fehlende/Fehlerhafte Angabe", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (!dpBis.SelectedDate.HasValue || dpBis.SelectedDate.Value < DateTime.Now.Date)
                    MessageBox.Show("Ende der Buchung muss korrekt gewählt sein", "Fehlende/Fehlerhafte Angabe", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (cbFirma.SelectedIndex == -1)
                    MessageBox.Show("Firma muss gewählt werden\n\nIst die korrekte Firma nicht vorhanden, muss diese zunächst unter Firmen verwalten angelegt werden", "Fehlende/Fehlerhafte Angabe", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    string buchungen = "";
                    int count = 0;

                    foreach (CalendarDateRange blackoutRange in dpVon.BlackoutDates)
                    {
                        // Prüfe auf Überschneidung
                        if (dpVon.SelectedDate.Value <= blackoutRange.End && dpBis.SelectedDate.Value >= blackoutRange.Start)
                        {
                            count++;
                            buchungen += ($"Überschneidung {count}:\t{blackoutRange.Start.ToString("dd.MM.yy")} - {blackoutRange.End.ToString("dd.MM.yy")}\n");
                        }
                    }

                    if (count > 0)
                    {
                        MessageBox.Show($"Diese Buchung überschneidet {(count == 1 ? "eine" : count.ToString())} vorhandene Buchung{(count > 0 ? "en" : "")}:\n\n{buchungen}", $"Überschneidung{(count > 0 ? "en" : "")}", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }



                    if (MessageBoxResult.Yes == MessageBox.Show($"Möchten Sie die\n\n{cbBE.Text}\n\nvom:\t{dpVon.Text}\nbis:\t{dpBis.Text}\n\nbuchen?", "Sicher buchen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
                    {
                        var beint = Helper.GetBENumbers()[cbBE.SelectedIndex - 1];

                        await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.beBelegung (beNr, beFlaeche, Projektleiter, von, bis, Bemerkung, idFirmen) VALUES (@beNr,@beFlaeche,@Projektleiter,@von,@bis,@Bemerkung,@idFirmen)", new List<MySqlParameter>()
                        {
                            new MySqlParameter("@beNr", beint),
                            new MySqlParameter("@beFlaeche", (cbBE.SelectedItem as ComboBoxItem).Content.ToString()),
                            new MySqlParameter("@Projektleiter", Environment.UserName),
                            new MySqlParameter("@von", dpVon.SelectedDate.Value.ToString("yyyy-MM-dd")),
                            new MySqlParameter("@bis", dpBis.SelectedDate.Value.ToString("yyyy-MM-dd")),
                            new MySqlParameter("@Bemerkung", tbBemerkung.Text),
                            new MySqlParameter("@idFirmen", cbFirma.SelectedValue ?? -1)
                        });

                        await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.firmen SET BEint = @beint, BE = @beFlaeche WHERE idFirmen = @idFirmen", new List<MySqlParameter>()
                        {
                            new MySqlParameter("@beint", beint),
                            new MySqlParameter("@beFlaeche", (cbBE.SelectedItem as ComboBoxItem).Content.ToString()),
                            new MySqlParameter("@idFirmen", cbFirma.SelectedValue ?? -1)
                        });
                    }

                    cbBE.SelectedIndex = -1;
                    dpVon.SelectedDate = null;
                    dpBis.SelectedDate = null;
                    tbBemerkung.Text = "";

                    lastAddedId = SQL.ReadSingleValue($"SELECT MAX(idbeBelegung) FROM {MainWindow.table}.beBelegung");
                    QueryBelegung();

                    timer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Es ist ein Fehler bei der Buchung aufgetreten", "Fehler", MessageBoxButton.OK, MessageBoxImage.Information);
                Log.WriteLog(ex.ToString());
            }
        }


        private async void tbDGBemerkung_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {

        }


        private async void tbDGBemerkung_LostFocus(object sender, RoutedEventArgs e)
        {
            dgBelegung.DataContextChanged -= dgBelegung_DataContextChanged;
            try
            {
                var arr = ((sender as TextBox).DataContext as DataRowView).Row.ItemArray;
                //await SQL.WriteSQL($"UPDATE {MainWindow.table}.beBelegung SET Bemerkung = '{(sender as TextBox).Text}' WHERE idbeBelegung = '{arr[0]}'");
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.beBelegung SET Bemerkung = @Bemerkung WHERE idbeBelegung = @arr0", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@Bemerkung", (sender as TextBox).Text),
                                                new MySqlParameter("@arr0", arr[0])
                                            });
                //
            }
            catch (Exception)
            {

            }
            dgBelegung.DataContextChanged += dgBelegung_DataContextChanged;
        }
        private async void dgBelegung_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            //BlackoutDates();
        }

        private async void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            var picker = (sender as DatePicker);
            var pickerName = picker.Name;
            var parent = Helper.FindParent<ContentPresenter>(picker);
            var id = (parent.DataContext as DataRowView).Row.ItemArray[0];


            if (picker.SelectedDate != null)
            {
                if (pickerName.ToLower().Contains("von"))
                {
                    //await SQL.WriteSQL($"UPDATE {MainWindow.table}.beBelegung SET von = '{picker.SelectedDate.Value.ToString("yyyy-MM-dd")}' WHERE idbeBelegung = {id}");
                    await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.beBelegung SET von = @picker WHERE idbeBelegung = @id", new List<MySqlParameter>()
                                                {
                                                    new MySqlParameter("@picker", picker.SelectedDate.Value.ToString("yyyy-MM-dd")),
                                                    new MySqlParameter("@id", id)
                                                });
                }
                else if (pickerName.ToLower().Contains("bis"))
                {
                    //await SQL.WriteSQL($"UPDATE {MainWindow.table}.beBelegung SET bis = '{picker.SelectedDate.Value.ToString("yyyy-MM-dd")}' WHERE idbeBelegung = {id}");
                    await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.beBelegung SET bis = @picker WHERE idbeBelegung = @id", new List<MySqlParameter>()
                                                {
                                                    new MySqlParameter("@picker", picker.SelectedDate.Value.ToString("yyyy-MM-dd")),
                                                    new MySqlParameter("@id", id)
                                                });
                }
            }

            //BlackoutDates();
            QueryBelegung();
        }

        private async void QueryBelegung()
        {
            Cursor = Cursors.Wait;

            var ldps = Helper.FindVisualChildren<DatePicker>(dgBelegung).ToList();

            foreach (var d in ldps)
            {
                d.SelectedDateChanged -= DatePicker_SelectedDateChanged;
            }

            if (cbBE.SelectedIndex == -1 || cbBE.SelectedIndex == 0)
            {
                await Task.Run(() =>
                {
                    be = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.beBelegung WHERE bis >= curdate() ORDER BY beNr ASC, bis ASC").Result;
                });    
                dgBelegung.DataContext = be;                
            }
            else
            {
                var index = cbBE.SelectedIndex;
                be = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.beBelegung WHERE bis >= curdate() AND beNr = '{Helper.GetBENumbers()[index - 1].TrimStart('0')}' ORDER BY beNr ASC, bis ASC").Result;                 
                
                dgBelegung.DataContext = be;
            }

            foreach (var d in ldps)
            {
                d.SelectedDateChanged += DatePicker_SelectedDateChanged;
            }

            await Dispatcher.BeginInvoke(new Action(() => DataGrid_Filled()));
        }



        private void cbFirma_TextInput(object sender, TextCompositionEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            string searchText = comboBox.Text;

            if (string.IsNullOrWhiteSpace(searchText))
            {
                var items = from DataRow row in firm.Rows
                            select new BEFirma
                            {
                                idFirmen = row["idFirmen"].ToString(),
                                Name = row["Name"].ToString(),
                                Beauftragte_Leistung = row["Beauftragte_Leistung"].ToString()
                            };                                                        
                
                //$"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)}') ORDER BY Name ASC").Result;

                comboBox.ItemsSource = items;
            }
            else
            {
                firm.DefaultView.RowFilter = $"Name LIKE '%{searchText}%'";
                //var filtered = firm.DefaultView.RowFilter($"Name LIKE %{searchText}%");
                //comboBox.ItemsSource = filtered;
            }

            comboBox.IsDropDownOpen = true;
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //BlackoutDates();

            var ldps = Helper.FindVisualChildren<DatePicker>(dgBelegung).ToList();

            foreach (var d in ldps)
            {
                d.SelectedDateChanged += DatePicker_SelectedDateChanged;
            }
        }



        private void dgBelegung_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(async () =>
            {
                BlackoutDates();
                Cursor = Cursors.Arrow;
            }
            ));
        }


        private void dpVonDG_Loaded(object sender, RoutedEventArgs e)
        {
            if (cbBE.SelectedIndex != 0 && cbBE.SelectedIndex != -1)
            {
                var dp = sender as DatePicker;
                if (dp.DataContext != null)
                {
                    var user = (dp.DataContext as DataRowView).Row.ItemArray[3].ToString();
                    if (user != Environment.UserName)
                    {
                        dp.IsEnabled = false;
                        dp.ToolTip = $"Gesperrt durch {Helper.InsertSpaceBeforeUpperCase(user)}";
                    }
                    else
                    {
                        dp.IsEnabled = true;
                        dp.ToolTip = "Start der Buchung";
                    }
                }
            }


            //BlackoutDates();  // Die Ausführung ist nur einmal nötig und wird in dpBisDG_Loaded abgearbeitet
        }

        private void dpBisDG_Loaded(object sender, RoutedEventArgs e)
        {
            if (cbBE.SelectedIndex != 0 && cbBE.SelectedIndex != -1)
            {
                var dp = (sender as DatePicker);
                if (dp.DataContext != null)
                {
                    var user = (dp.DataContext as DataRowView).Row.ItemArray[3].ToString();
                    if (user != Environment.UserName)
                    {
                        dp.IsEnabled = false;
                        dp.ToolTip = $"Gesperrt durch {Helper.InsertSpaceBeforeUpperCase(user)}";
                    }
                    else
                    {
                        dp.IsEnabled = true;
                        dp.ToolTip = "Ende der Buchung";
                    }
                }
            }
        }

        private void tbDGBemerkung_Loaded(object sender, RoutedEventArgs e)
        {
            if (cbBE.SelectedIndex != 0 && cbBE.SelectedIndex != -1)
            {
                var tb = sender as TextBox;
                if (tb.DataContext != null)
                {
                    var user = (tb.DataContext as DataRowView).Row.ItemArray[3].ToString();
                    if (user != Environment.UserName)
                    {
                        tb.IsEnabled = false;
                        tb.ToolTip = $"Gesperrt durch {Helper.InsertSpaceBeforeUpperCase(user)}";
                    }
                    else
                    {
                        tb.IsEnabled = true;
                        tb.ToolTip = "Maßnahme/Bemerkung";
                    }
                }
            }

        }

        private void cbFirma_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if((sender as ComboBox).SelectedIndex == (sender as ComboBox).Items.Count - 1)
            {
                (sender as ComboBox).SelectedIndex = -1;

                CreateFirma cFa = new CreateFirma();
                cFa.ShowDialog();


                FillFirmen();
            }
        }

        private void DelButton_Loaded(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var user = (btn.DataContext as DataRowView).Row.ItemArray[3].ToString();
            if (user != Environment.UserName)
            {
                btn.IsEnabled = false;
                btn.Foreground = new SolidColorBrush(Colors.Gray);
                btn.ToolTip = $"Gesperrt durch {Helper.InsertSpaceBeforeUpperCase(user)}";
            }
            else
            {
                btn.IsEnabled = true;
                btn.Foreground = new SolidColorBrush(Colors.Red);
                btn.ToolTip = $"Buchung stornieren";
            }
        }




        private void btnCurrentlyBooked_Click(object sender, RoutedEventArgs e)
        {
            if (btnCurrentlyBooked.Content.ToString() == "Alle gebuchten Flächen anzeigen")
            {
                be = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.beBelegung WHERE bis >= curdate() ORDER BY beNr ASC, bis ASC").Result;
                dgBelegung.DataContext = be;


                cbBE.SelectionChanged -= cbBE_SelectionChanged;
                cbBE.SelectedIndex = 0;
                cbBE.SelectionChanged += cbBE_SelectionChanged;


                btnCurrentlyBooked.Content = "Aktuell belegte Flächen anzeigen";
                lblBE.Text = "Alle aktuell gebuchten BE-Flächen:";
            }
            else
            {
                be = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.beBelegung WHERE von <= curdate() AND bis >= curdate() ORDER BY beNr ASC, bis ASC").Result;
                dgBelegung.DataContext = be;


                cbBE.SelectionChanged -= cbBE_SelectionChanged;
                cbBE.SelectedIndex = 0;
                cbBE.SelectionChanged += cbBE_SelectionChanged;


                btnCurrentlyBooked.Content = "Alle gebuchten Flächen anzeigen";
                lblBE.Text = $"Am {DateTime.Now.ToString("dd.MM.yy")} belegte Flächen:";
            }
        }

        private async void InfoButton_Click(object sender, RoutedEventArgs e)
        {
            if (pop.IsOpen)
            {
                pop.IsOpen = false;
                //(sender as Button).ClearValue(Button.BackgroundProperty);
                (sender as Button).ClearValue(Button.ForegroundProperty);
                (sender as Button).Content = "ⓘ";
            }
            else
            {
                var be = ((sender as Button).DataContext as DataRowView).Row.ItemArray[2].ToString();
                var id = ((sender as Button).DataContext as DataRowView).Row.ItemArray[7].ToString();
                var Firma = await SQL.ReadSQL($"SELECT Name, Verantwortlicher_MA_Firma, Tel_Nr_Verantwortlicher_Firma, Anzahl_Fzg,Beauftragte_Leistung,Arbeitsbeginn, Arbeitsende,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern FROM {MainWindow.table}.firmen WHERE idFirmen = '{(string.IsNullOrWhiteSpace(id) ? "0" : id)}'");
                var Firmen = await SQL.ReadSQL($"SELECT Name, Verantwortlicher_MA_Firma, Tel_Nr_Verantwortlicher_Firma, Anzahl_Fzg,Beauftragte_Leistung,Arbeitsbeginn, Arbeitsende,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern FROM {MainWindow.table}.firmen WHERE BE = '{be}' AND Arbeitsende >= curdate() AND idFirmen <> '{(string.IsNullOrWhiteSpace(id) ? "0" : id)}'");/* AND Ersteller = '{Environment.UserName}'*/

                Firma.Merge(Firmen);
                dgFirmen.DataContext = Firma;

                (sender as Button).Content = "✕";
                (sender as Button).Foreground = new SolidColorBrush(Colors.Red);
                //(sender as Button).Background = new SolidColorBrush(Colors.DarkGray);
                //var pop = new Popup();
                pop.PopupAnimation = PopupAnimation.Slide;
                pop.PlacementTarget = (sender as Button);
                pop.HorizontalOffset = 50;

                pop.IsOpen = true;
                lastInfoButton = sender as Button;
            }
        }

        Button lastInfoButton;
        private void Pop_Closed(object sender, EventArgs e)
        {
            if (lastInfoButton != null)
            {
                lastInfoButton.ClearValue(Button.BackgroundProperty);
                lastInfoButton.Content = "ⓘ";
            }
        }

        private void MetroWindow_Closing(object sender, CancelEventArgs e)
        {
            pop.IsOpen = false;
        }
        private async void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            var arr = ((sender as Button).DataContext as DataRowView).Row.ItemArray;
            var id = arr[0].ToString();
            var be = arr[2].ToString();
            var von = arr[4].ToString().Split(' ')[0];
            var bis = arr[5].ToString().Split(' ')[0];

            if (MessageBoxResult.Yes == MessageBox.Show($"Wollen Sie die Buchung für\n\n{be}\n\nvom:\t{von}\nbis:\t{bis}\n\nsicher stornieren?", "Buchung stornieren?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
            {
                Cursor = Cursors.Wait;

                try
                {
                    await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.beBelegung WHERE idbeBelegung = {id}");
                }
                catch (Exception ex)
                {
                    Log.WriteLog(ex.ToString());
                    MessageBox.Show("Es ist ein Fehler beim Löschen aufgetreten, bitte erneut versuchen", "Fehler beim Löschen", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                QueryBelegung();
            } 
        }

        private void dpBisDG_LostFocus(object sender, RoutedEventArgs e)
        {

        }

        private void dpBis_LostFocus(object sender, RoutedEventArgs e)
        {
            var dp = sender as DatePicker;
            if (dp.SelectedDate.HasValue)
            {
                if (dp.SelectedDate.Value < DateTime.Now.Date)
                {
                    MessageBox.Show("Das Ende der Buchung kann nicht in der Vergangenheit liegen", "Ungültiges Datum", MessageBoxButton.OK, MessageBoxImage.Error);
                    dp.SelectedDate = null;
                }

                if (dpVon.SelectedDate.HasValue && dp.SelectedDate != null && dp.SelectedDate.Value < dpVon.SelectedDate.Value)
                {
                    MessageBox.Show("Das Ende der Buchung kann nicht vor dem Start liegen", "Ungültiges Datum", MessageBoxButton.OK, MessageBoxImage.Error);
                    dp.SelectedDate = dpVon.SelectedDate.Value;
                }
            }
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Helper.CheckWindowIsInScreenSpace(this);
        }

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

    public class BEFirma
    {
        public string idFirmen { get; set; }
        public string Name { get; set; }
        public string Beauftragte_Leistung { get; set; }

        public override string ToString()
        {
            return $"{Name}  -  Auftrag: {Beauftragte_Leistung}";
        }
    }
}
