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.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 ApproveFzg.xaml
    /// </summary>
    public partial class ApproveFzg : MetroWindow
    {
        DataTable Fzg = new DataTable("Fzg");

        public ApproveFzg()
        {
            this.DataContext = this;

            InitializeComponent();

            Fzg = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.fzgAnmeldung").Result;

            dgFzg.DataContext = Fzg;
        }

  
        private async void InfoButton_Click(object sender, RoutedEventArgs e)
        {
            var buttons = Helper.FindVisualChildren<Button>(dgFzg).Where(p => p.Content != null && p.Content.ToString() == "✕");

            foreach (var b in buttons)
            {
                b.ClearValue(Button.BackgroundProperty);
                b.Content = "ⓘ";
            }

            if (!pop.IsOpen)
            {
                var id = ((sender as Button).DataContext as DataRowView).Row.ItemArray[1].ToString();

                var Firmen = await SQL.ReadSQL($"SELECT Name,Verantwortlicher_MA_Firma,Tel_Nr_Verantwortlicher_Firma,Anzahl_Begleiter,Beauftragte_Leistung,Arbeitsbeginn,Arbeitsende,Ansprechpartner_Intern,Tel_Nr_Ansprechpartner_Intern,BE FROM {MainWindow.table}.firmen WHERE idFirmen = '{id}'");
                dgFirmen.DataContext = Firmen;

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

                pop.IsOpen = true;
            }
            else
            {
                (sender as Button).ClearValue(Button.BackgroundProperty);
                (sender as Button).Content = "ⓘ";

                pop.IsOpen = false;
            }
        }
        private void MetroWindow_Closing(object sender, CancelEventArgs e)
        {
            pop.IsOpen = false;
        }

        private async void ApproveButton_Click(object sender, RoutedEventArgs e)
        {
            var arr = ((sender as Button).DataContext as DataRowView).Row.ItemArray;
            var id = arr[0].ToString();
            var anzFzg = arr[2].ToString();
            var user = Helper.InsertSpaceBeforeUpperCase(arr[3].ToString());

            if (MessageBoxResult.Yes == MessageBox.Show($"Antrag\t{id}\nvon:\t{user}\nmit:\t{anzFzg} Fahrzeugen\n\nsicher genehmigen?", "Sicher genehmigen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
            {
                //await SQL.WriteSQL($"UPDATE {MainWindow.table}.fzgAnmeldung SET Genehmigung = '1' WHERE idfzgAnmeldung = '{id}'");
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.fzgAnmeldung SET Genehmigung = '1' WHERE idfzgAnmeldung = @id", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@id", id)
                                            });

                Fzg = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.fzgAnmeldung").Result;
                dgFzg.DataContext = Fzg;
            }
        }

        private async void DeclineButton_Click(object sender, RoutedEventArgs e)
        {
            var arr = ((sender as Button).DataContext as DataRowView).Row.ItemArray;
            var id = arr[0].ToString();
            var anzFzg = arr[2].ToString();
            var user = Helper.InsertSpaceBeforeUpperCase(arr[3].ToString());

            if (MessageBoxResult.Yes == MessageBox.Show($"Antrag\t{id}\nvon:\t{user}\nmit:\t{anzFzg} Fahrzeugen\n\nsicher ablehnen?", "Sicher ablehnen?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
            {
                //await SQL.WriteSQL($"UPDATE {MainWindow.table}.fzgAnmeldung SET Genehmigung = '2' WHERE idfzgAnmeldung = '{id}'");
                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.fzgAnmeldung SET Genehmigung = '2' WHERE idfzgAnmeldung = @id", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@id", id)
                                            });

                Fzg = SQL.ReadSQL($"SELECT * FROM {MainWindow.table}.fzgAnmeldung").Result;
                dgFzg.DataContext = Fzg;
            }
        }

        private void pop_Closed(object sender, EventArgs e)
        {
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var count = SQL.ReadSingleValue($"SELECT count(idfzgAnmeldung) FROM {MainWindow.table}.fzgAnmeldung WHERE Timestamp < now() - INTERVAL 30 DAY");

            if (Convert.ToInt16(count) > 0)
            {
                SQL.WriteSQL($"DELETE FROM {MainWindow.table}.fzgAnmeldung WHERE Timestamp < now() - INTERVAL 30 DAY AND Genehmigung <> 0");

                popDeleted.Opacity = 0;
                popDeleted.Visibility = Visibility.Visible;
                tbDeleted.Text = $"{count} Einträge (älter als 30 Tage) wurden gelöscht";

                (this.Resources["popDeleted"] as System.Windows.Media.Animation.Storyboard).Begin();
            }
        }

        private void Storyboard_Completed(object sender, EventArgs e)
        {
            popDeleted.Visibility = Visibility.Collapsed;
        }


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

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