using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.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 CreateVisitor_List.xaml
    /// </summary>
    public partial class CreateVisitor_List : MetroWindow
	{
        //private List<Visitor> myVar;
        //public List<Visitor> VisitorView
        //{
        //    get { return myVar; }
        //    set { myVar = value; }
        //}

        DataTable visitors = new DataTable("Visitors");


        int index = 0;

        public CreateVisitor_List()
        {
            this.DataContext = this;

            InitializeComponent();

            this.Title = "Besucherliste von: " + Helper.InsertSpaceBeforeUpperCase(Environment.UserName);

            visitors = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.besucher WHERE Ersteller = '{Environment.UserName}'", visitors).Result;
            //VisitorView = Visitor.DataTableToVisitor(visitors);
            dgVisitors.DataContext = visitors;

            dgVisitors.Items.SortDescriptions.Clear();
            dgVisitors.Items.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            dgVisitors.UpdateLayout();


        }

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

        private async void DgVisitors_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];
            DateTime date = DateTime.Now;

            if (DateTime.TryParseExact(newValue, "dd.MM.yyyy", null, System.Globalization.DateTimeStyles.None, out date))
                newValue = date.ToString("yyyy-MM-dd");

            var MessageValue = newValue;
            var MessageDate = DateTime.Now;
            if (DateTime.TryParse(newValue, out MessageDate))
                MessageValue = MessageDate.ToString("dd.MM.yyyy");

            if (oldValue != MessageValue)
            {
                if (MessageBox.Show(this, $"Möchten Sie den Eintrag '{oldValue}' in der Spalte '{header}' sicher zu '{MessageValue}' ändern?", "Sicher ändern?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    switch (header)
                    {
                        case "Name":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Name = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Verantw. MA":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Verantwortlicher_MA = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Tel. Besucher":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Tel_Nr_Besucher = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Anz. Begleitp.":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Anzahl_Begleitpersonen = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Besuchstag":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Besuchstag = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Grund des Besuchs":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Grund_des_Besuchs = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Örtlichkeit":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Oertlichkeit = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Anspr. intern":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Ansprechpartner_Intern = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                        case "Tel. Ansprechp.":
                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.besucher SET Tel_Nr_Ansprechpartner_Intern = '{newValue}', Bearbeiter = '{Environment.UserName}' WHERE idBesucher = '{id}'");
                            break;
                    }
                }
            }

            index = e.Row.GetIndex();
            dgVisitors.PreviewKeyDown += DgVisitors_PreviewKeyDown;

            visitors = SQL.ReadSQL($"Select * from {MainWindow.table}.besucher WHERE Ersteller = '{Environment.UserName}'", visitors).Result;
            //VisitorView = Visitor.DataTableToVisitor(visitors);


            dgVisitors.RowValidationErrorTemplate = new ControlTemplate();

            dgVisitors.SelectedIndex = (index);
            dgVisitors.ScrollIntoView(dgVisitors.Items[index]);

            //ScrollTo();
        }

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

            if (e.Key == Key.Delete)
            {
                deleteRow(arr);
            }
        }

        private void DgVisitors_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            dgVisitors.PreviewKeyDown -= DgVisitors_PreviewKeyDown;
        }

        string oldValue = "";
        private void dgVisitors_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            oldValue = (e.EditingElement as TextBox) != null ? (e.EditingElement as TextBox).Text : "";
        }

        private void dgVisitors_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgVisitors.SelectedIndex != -1) btnDelete.IsEnabled = true;
            else btnDelete.IsEnabled = false;

        }

        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var dg = dgVisitors;
            var row = dg.SelectedItem as DataRowView;
            var arr = row.Row.ItemArray;

            if (MessageBox.Show(this, $"Markierten Besucher wirklich entfernen?", "Besucher entfernen?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                deleteRow(arr);
            }
        }

        private async void deleteRow(object[] arr)
        {
            //await SQL.WriteSQL($"INSERT INTO {MainWindow.table}.besucherLog (idbesucher, Name,Verantwortlicher_MA,Tel_Nr_Besucher,Anzahl_Begleitpersonen,Besuchstag,Grund_des_Besuchs,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern,Oertlichkeit,Geloescht_Von) VALUES " +
            //                                $"('{arr[0]}','{arr[1].ToString()}','{arr[2].ToString()}','{arr[3].ToString()}','{arr[4].ToString()}','{Convert.ToDateTime(arr[5].ToString()).ToString("yyyy-MM-dd")}','{arr[6].ToString()}','{arr[7].ToString()}','{arr[8].ToString()}','{arr[10].ToString()}','{Environment.UserName}')");
            await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.besucherLog (idbesucher, Name,Verantwortlicher_MA,Tel_Nr_Besucher,Anzahl_Begleitpersonen,Besuchstag,Grund_des_Besuchs,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern,Oertlichkeit,Geloescht_Von) VALUES (@arr0,@arr1,arr2,@arr3,@arr4,@arr5,@arr6,@arr7,@arr8,@arr10,@UserName)", new List<MySqlParameter>()
                                        {
                                            new MySqlParameter("@arr0", arr[0]),
                                            new MySqlParameter("@arr1", arr[1].ToString()),
                                            new MySqlParameter("@arr2", arr[2].ToString()),
                                            new MySqlParameter("@arr3", arr[3].ToString()),
                                            new MySqlParameter("@arr4", arr[4].ToString()),
                                            new MySqlParameter("@arr5", Convert.ToDateTime(arr[5].ToString()).ToString("yyyy-MM-dd")),
                                            new MySqlParameter("@arr6", arr[6].ToString()),
                                            new MySqlParameter("@arr7", arr[7].ToString()),
                                            new MySqlParameter("@arr8", arr[8].ToString()),
                                            new MySqlParameter("@arr10", arr[10].ToString()),
                                            new MySqlParameter("@UserName", Environment.UserName)
                                        });



            await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.besucher WHERE `idbesucher` = '{arr[0]}'");

            visitors = SQL.ReadSQL($"Select * from {MainWindow.table}.besucher WHERE Ersteller = '{Environment.UserName}'", visitors).Result;
            //VisitorView = Visitor.DataTableToVisitor(visitors);
        }



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

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