using ControlzEx.Standard;
using FuzzySharp;
using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
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;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für ManageDeliveries.xaml
    /// </summary>
    public partial class ManageDeliveries : MetroWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        //private List<Deliver> myVar;
        //public List<Deliver> DeliveriesView
        //{
        //    get { return myVar; }
        //    set { myVar = value; OnPropertyChanged(); }
        //}
        System.Data.DataTable lieferanten = new System.Data.DataTable("lieferanten");

        public ManageDeliveries()
        {
            InitializeComponent();

            lieferanten = SQL.ReadSQL($"Select * from {MainWindow.table}.lieferanten", lieferanten).Result;
            //DeliveriesView = Deliver.DataTableToDeliver(lieferanten);
            dgLieferanten.DataContext = lieferanten;

            dgLieferanten.Items.SortDescriptions.Clear();
            dgLieferanten.Items.SortDescriptions.Add(new SortDescription("Firma", ListSortDirection.Ascending));
            dgLieferanten.Items.Refresh();
        }

        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbFirma.Text))
            {
                MessageBox.Show(this, "Lieferfirma muss eingetragen werden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            else
            {
                //await SQL.WriteSQL($"INSERT INTO {MainWindow.table}.lieferanten (Firma, Fahrer, Handynr, Kennzeichen) VALUES ('{tbFirma.Text}','{tbFahrer.Text}','{tbHandynr.Text}','{tbKennzeichen.Text}')");
                await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.lieferanten (Firma, Fahrer, Handynr, Kennzeichen, EingetragenVon) VALUES (@tbFirma,@tbFahrer,@tbHandynr,@tbKennzeichen,@eingetragenVon)", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@tbFirma", tbFirma.Text),
                                                new MySqlParameter("@tbFahrer", tbFahrer.Text),
                                                new MySqlParameter("@tbHandynr", tbHandynr.Text),
                                                new MySqlParameter("@tbKennzeichen", tbKennzeichen.Text),
                                                new MySqlParameter("@eingetragenVon", Environment.UserName)
                                            });


                lieferanten = SQL.ReadSQL($"Select * from {MainWindow.table}.lieferanten", lieferanten).Result;
                //DeliveriesView = Deliver.DataTableToDeliver(lieferanten);
                dgLieferanten.ScrollIntoView(dgLieferanten.Items[dgLieferanten.Items.Count - 1]); //scroll to last
                dgLieferanten.UpdateLayout();
                ResetInput();
            }
        }


        private void ResetInput()
        {
            tbFirma.Text = "";
            tbFahrer.Text = "";
            tbHandynr.Text = "";
            tbKennzeichen.Text = "";
        }

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


        private async void dgLieferanten_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (string.IsNullOrWhiteSpace((e.EditingElement as TextBox).Text)) return;

            var header = e.Column.Header;
            var newValue = (e.EditingElement as TextBox).Text;
            var id = (e.Row.Item as System.Data.DataRowView).Row.ItemArray[4];

            string searchFahrer = "";

            if ((e.Row.Item as System.Data.DataRowView).Row.ItemArray[1].ToString() != "")
                searchFahrer = $" AND Fahrer = '{(e.Row.Item as System.Data.DataRowView).Row.ItemArray[1].ToString()}'";

            switch (header)
            {
                case "Firma":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.lieferanten SET Firma = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `ID` = '{id}'");// + searchFahrer);
                    break;
                case "Fahrer":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.lieferanten SET Fahrer = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `ID` = '{id}'");// + searchFahrer);
                    break;
                case "Handynr":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.lieferanten SET Handynr = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `ID` = '{id}'");// + searchFahrer);
                    break;
                case "Kennzeichen":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.lieferanten SET Kennzeichen = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `ID` = '{id}'");// + searchFahrer);
                    break;
            }

            dgLieferanten.PreviewKeyDown += DgLieferanten_PreviewKeyDown;

            lieferanten = await SQL.ReadSQL($"Select * from {MainWindow.table}.lieferanten", lieferanten);
            //DeliveriesView = Deliver.DataTableToDeliver(lieferanten);
        }


        private async void DgLieferanten_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var dg = sender as DataGrid;
            var row = dg.SelectedItem as System.Data.DataRowView;
            var arr = row.Row.ItemArray;

            if (e.Key == Key.Delete)
            {
                await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.lieferanten WHERE `ID` = '{arr[4]}'");

                lieferanten = SQL.ReadSQL($"Select * from {MainWindow.table}.lieferanten", lieferanten).Result;
                //DeliveriesView = Deliver.DataTableToDeliver(lieferanten);
            }
        }

        private void dgLieferanten_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            dgLieferanten.PreviewKeyDown -= DgLieferanten_PreviewKeyDown;
        }


        private async void btnDeleteDeliver_Click(object sender, RoutedEventArgs e)
        {
            var dg = dgLieferanten;
            var row = dg.SelectedItem as System.Data.DataRowView;
            var arr = row.Row.ItemArray;

            if (MessageBox.Show(this, $"Markierten Lieferanten wirklich entfernen?", "Lieferanten entfernen?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.lieferanten WHERE `ID` = '{arr[4]}'");

                lieferanten = SQL.ReadSQL($"Select * from {MainWindow.table}.lieferanten", lieferanten).Result;
                //DeliveriesView = Deliver.DataTableToDeliver(lieferanten);
            }
        }

        private void dgLieferanten_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgLieferanten.SelectedIndex != -1) btnDeleteDeliver.IsEnabled = true;
            else btnDeleteDeliver.IsEnabled = false;
        }


        ToolTip tt = new ToolTip();
        private void TextBoxes_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var input = (sender as TextBox).Text;
            if (input.ToLower().Contains("db") ||
                input.ToLower() == "service")
            {
                tt.Placement = PlacementMode.RelativePoint;
                tt.PlacementTarget = (sender as TextBox);
                tt.VerticalOffset = (sender as TextBox).Height;
                //tt.Width = (sender as TextBox).Width;
                tt.Background = new SolidColorBrush(Colors.Red);
                tt.Content = new Grid();
                (tt.Content as Grid).Background = new SolidColorBrush(Colors.Red);
                (tt.Content as Grid).Children.Add(new TextBlock() { Text = "DB Firmen dürfen nicht als Lieferant angelegt werden!!" });

                tt.IsOpen = true;
                (sender as TextBox).ToolTip = tt;
            }
            else
            {
                tt.IsOpen = false;
                (sender as TextBox).ToolTip = null;
            }

            if (e.Key != Key.OemComma)
            {
                e.Handled = false;
                return;
            }
            else
            {
                MessageBox.Show(this, "Komma (',') ist ein nicht erlaubtes Zeichen", "Achtung", MessageBoxButton.OK, MessageBoxImage.Information);
                e.Handled = true;
            }
            return;
        }



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

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

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            System.Diagnostics.Debug.WriteLine("PropertyChanged   " + propertyName);
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }




    //public class Deliver
    //{
    //    public string Firma;
    //    string Fahrer;
    //    string Handynr;
    //    string Kennzeichen;




    //    public static List<Deliver> DataTableToDeliver(System.Data.DataTable dataTable)
    //    {
    //        List<Deliver> x = new List<Deliver>();

    //        foreach (System.Data.DataRow dr in dataTable.Rows)
    //        {
    //            x.Add(new Deliver()
    //            {
    //                Firma = dr[0].ToString(),
    //                Fahrer = dr[1].ToString(),
    //                Handynr = dr[2].ToString(),
    //                Kennzeichen = dr[3].ToString()
    //            });
    //        }

    //        return x;
    //    }
    //}
}
