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.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 ManageEntstoerdienste.xaml
    /// </summary>
    public partial class ManageEntstoerdienste : MetroWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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


        public ManageEntstoerdienste()
        {
            InitializeComponent();


            var list = new List<string>()
                {
                    "DB Energie",
                    "DB InfraGO",
                    "DB KT",
                    "DB Postservice",
                    "Gerätewagen"
                };

            cbFirma.ItemsSource = list;

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

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

        private async void dgEntstoerdienste_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[0];

            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}.entstoerdienste SET Firma = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `identstoerdienste` = '{id}'");// + searchFahrer);
                    break;
                case "Fahrer":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.entstoerdienste SET Fahrer = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `identstoerdienste` = '{id}'");// + searchFahrer);
                    break;
                case "Handynr":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.entstoerdienste SET Handynr = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `identstoerdienste` = '{id}'");// + searchFahrer);
                    break;
                case "Kennzeichen":
                    await SQL.WriteSQL($"UPDATE {MainWindow.table}.entstoerdienste SET Kennzeichen = '{newValue}', GeändertVon = '{Environment.UserName}' WHERE `identstoerdienste` = '{id}'");// + searchFahrer);
                    break;
            }

            dgEntstoerdienste.PreviewKeyDown += DgEntstoerdienste_PreviewKeyDown;

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

        private async void DgEntstoerdienste_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}.entstoerdienste WHERE `identstoerdienste` = '{arr[0]}'");

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

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

        private void dgEntstoerdienste_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            dgEntstoerdienste.PreviewKeyDown -= DgEntstoerdienste_PreviewKeyDown;
        }

        private async void dgEntstoerdienste_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}.entstoerdienste WHERE `identstoerdienste` = '{arr[0]}'");

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

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

            if (MessageBox.Show(this, $"Markierten Entstördienst wirklich entfernen?", "Entstördienst entfernen?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.entstoerdienste WHERE `identstoerdienste` = '{arr[0]}'");

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

        private void TextBoxes_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            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;
            }
        }

        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(cbFirma.Text))
            {
                MessageBox.Show(this, "DB Firma 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}.entstoerdienste (Firma, Fahrer, Handynr, Kennzeichen, EingetragenVon) VALUES (@tbFirma,@tbFahrer,@tbHandynr,@tbKennzeichen,@eingetragenVon)", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@tbFirma", cbFirma.Text),
                                                new MySqlParameter("@tbFahrer", tbFahrer.Text),
                                                new MySqlParameter("@tbHandynr", tbHandynr.Text),
                                                new MySqlParameter("@tbKennzeichen", tbKennzeichen.Text),
                                                new MySqlParameter("@eingetragenVon", Environment.UserName)
                                            });


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


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

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