using ControlzEx.Standard;
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.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;
using System.Windows.Threading;

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


        System.Data.DataTable karten = new System.Data.DataTable("karten");
        System.Data.DataTable mcFit = new System.Data.DataTable("mcFit");




        DispatcherTimer textInputTimer = new DispatcherTimer();

        byte[] _signature = null;


        public Cards()
        {
            InitializeComponent();


            textInputTimer.Interval = TimeSpan.FromSeconds(0.5);
            textInputTimer.Tick += TextInputTimer_Tick;
        }

        private async void dgCards_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete) await DeleteCard();
        }

        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            AddCardUser addCardUser = new AddCardUser();
            addCardUser.Owner = this;
            addCardUser.ShowDialog();


            await Query(CardType.DB);
        }



        private void CheckBoxHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CheckAllBoxes();
        }

        //private void CheckBox_Click(object sender, RoutedEventArgs e)
        //{
        //    var x = (sender as CheckBox).Parent;
        //    //((sender as CheckBox).Parent as DataRowView).Row.ItemArray[7] = !(bool)((sender as CheckBox).Parent as DataRowView).Row.ItemArray[7];
        //}


        private void CheckAllBoxes(bool init = false)
        {
            bool anyChecked = false;

            if (init)
            {
                anyChecked = true;
            }
            else
            {
                foreach (var row in dgCards.Items.Cast<DataRowView>())
                    if (row.Row.Field<bool?>("IsChecked") == true)
                    {
                        anyChecked = true;
                        break;
                    }
            }
                //anyChecked = dgCards.Items.Cast<DataRowView>().Any(row => row.Row.Field<bool?>("IsChecked") == true);

            foreach (DataRowView row in dgCards.Items)
            {
                row["IsChecked"] = !anyChecked;
            }
        }

        private void dgCards_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgCards.SelectedIndex != -1) btnDelete.IsEnabled = true;
            else btnDelete.IsEnabled = false;
        }
        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            await DeleteCard();
        }

        private async Task DeleteCard()
        {
            var dg = dgCards;
            var row = dg.SelectedItem as System.Data.DataRowView;
            var arr = row.Row.ItemArray;

            string cardsQuery = "";
            string cardsQueryTimestamp = "";
            string rueckgeber = "";

            for (int i = 0; i < dg.Items.Count; i++)
            {
                DataRowView item = dg.Items[i] as DataRowView;
                var r = dg.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (r != null)
                {
                    var content = dg.Columns[0].GetCellContent(r);
                    if ((content as CheckBox).IsChecked != null)
                    {
                        var mycheckbox = content as CheckBox;
                        if ((bool)mycheckbox.IsChecked)
                        {
                            cardsQuery += (item as DataRowView).Row.ItemArray[0].ToString() + ";";
                            cardsQueryTimestamp += (item as DataRowView).Row.ItemArray[5].ToString() + ";";

                            if (!string.IsNullOrWhiteSpace((item as DataRowView).Row.ItemArray[7].ToString()))
                                rueckgeber = (item as DataRowView).Row.ItemArray[7].ToString();
                        }
                    }
                }
            }

            if (cardsQuery == "")
            {
                if (MessageBox.Show(this, $"Karte {arr[1]},\nausgegeben an {arr[3]} wurde zurückgegeben?\n\nUnterschrift des Zurückgebers wird abgefragt...", "Karte zurückgegeben?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    var sig = new Signature(Signature.DisclaimerType.Rueck, arr[3].ToString(), arr[1].ToString(), "", true, arr[7].ToString());

                    if (sig.ShowDialog() == false)
                    {
                        _signature = sig.ResultByte;

                        if (_signature != null)
                        {
                            await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.karten WHERE `kartennr` = '{arr[1]}'");


                            await Query(CardType.DB);

                            //await SQL.WriteSQL($"UPDATE {MainWindow.table}.kartenLog SET RueckgabeSignature = @signature, Ansprechpartner = '{arr[7]}' WHERE idkarten = '{arr[0]}' AND Ausgebucht = 1 AND `timestamp` > (now() - INTERVAL 2 MINUTE)", _signature);
                            var cmd = SQL.CreateAndReturnSQLCommand($"UPDATE {MainWindow.table}.kartenLog SET RueckgabeSignature = @signature, Ansprechpartner = @arr7 WHERE idkarten = @arr0 AND Ausgebucht = '1' AND `timestamp` > (now() - INTERVAL 2 MINUTE)", new List<MySqlParameter>()
                                                        {
                                                            new MySqlParameter("@arr7", arr[7]),
                                                            new MySqlParameter("@arr0", arr[0])
                                                        });

                            await SQL.CreateAndWriteSQLwithSignature(cmd, _signature);

                            this.Close();
                        }
                    }
                }
            }
            else
            {
                string cards = "";
                string delCards = "";
                string delCardsLog = "";
                for(var i = 0; i < cardsQuery.Split(';').Length - 1; i++)
                {
                    cards += $"{cardsQuery.Split(';')[i].Trim()}   ausgegeben am: {cardsQueryTimestamp.Split(';')[i]}\n";
                    delCards += $"`kartennr` = '{cardsQuery.Split(';')[i].Trim()}' OR ";

                    delCardsLog += $"(`kartennr` = '{cardsQuery.Split(';')[i].Trim()}' AND Ausgebucht = 1 AND `timestamp` > (now() - INTERVAL 2 MINUTE)) OR ";
                }
                int lastIndex = delCards.LastIndexOf(" OR ");
                if (lastIndex != -1) delCards = delCards.Remove(lastIndex);

                int lastIndexLog = delCardsLog.LastIndexOf(" OR ");
                if (lastIndexLog != -1) delCardsLog = delCardsLog.Remove(lastIndexLog);

                if (MessageBox.Show(this, $"Die Karten\n\n{cards}\nwurden zurückgegeben?\n\nUnterschrift des Zurückgebers wird abgefragt...", "Karten zurückgegeben?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
                {
                    var sig = new Signature(Signature.DisclaimerType.Rueck, arr[3].ToString(), arr[1].ToString(), "", true, rueckgeber);

                    if (sig.ShowDialog() == false)
                    {
                        _signature = sig.ResultByte;

                        if (_signature != null)
                        {
                            await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.karten WHERE {delCards}");


                            await Query(CardType.DB);

                            await SQL.WriteSQL($"UPDATE {MainWindow.table}.kartenLog SET RueckgabeSignature = @signature WHERE {delCardsLog}", _signature);
                            //var cmd = SQL.CreateAndReturnSQLCommand($"UPDATE {MainWindow.table}.kartenLog SET RueckgabeSignature = @signature WHERE @delCardsLog", new List<MySqlParameter>()
                            //                                        {
                            //                                            new MySqlParameter("@delCardsLog", delCardsLog)
                            //                                        });

                            //await SQL.CreateAndWriteSQLwithSignature(cmd, _signature);

                            this.Close();
                        }
                    }
                }
            }
        }






        //
        //
        //
        //      
        //      McFIT
        //
        //
        //


        TextBox lastTextBox = null;

        private async void TextInputTimer_Tick(object sender, EventArgs e)
        {
            textInputTimer.Stop();

            var cBItemSource = await SQL.ReadListStringMultipleColumns($"SELECT idmcFitUsers, Name, Vorname FROM {MainWindow.table}.mcFitUsers WHERE `Name` LIKE '{lastTextBox.Text}%'");
            List<string> temp = new List<string>();

            foreach (var line in cBItemSource)
                temp.Add(line.Replace(";", " "));

            Dispatcher.Invoke(() =>
            {
                cBNameAusgabe.ItemsSource = temp;
                cBNameAusgabe.IsDropDownOpen = true;
            });
        }

        private void tbAusNachname_TextChanged(object sender, TextChangedEventArgs e)
        {
            lastTextBox = (sender as TextBox);

            textInputTimer.Start();
        }

        private async void cBNameAusgabe_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cBNameAusgabe != null && cBNameAusgabe.SelectedItem != null)
            {
                var result = await SQL.ReadListStringMultipleColumns($"SELECT Name,Vorname,Abteilung,Handynr,Email FROM {MainWindow.table}.mcFitUsers WHERE idmcFitUsers = '{cBNameAusgabe.SelectedItem.ToString().Split(' ')[0]}'", 5);

                tbAusNachname.TextChanged -= tbAusNachname_TextChanged;

                tbAusNachname.Text = result.First().Split(';')[0];
                tbAusVorname.Text = result.First().Split(';')[1];
                tbAusAbteilung.Text = result.First().Split(';')[2];
                tbAusHandy.Text = result.First().Split(';')[3];
                tbAusEmail.Text = result.First().Split(';')[4];

                tbAusNachname.TextChanged += tbAusNachname_TextChanged;
            }
        }

        private async void cBZurKarte_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int Kartennr = Convert.ToInt32(cBZurKarte.SelectedValue.ToString().Split(' ')[2]);

            var result = await SQL.ReadListStringMultipleColumns($"SELECT Nachname,Vorname,Abteilung,Handynr,Email FROM {MainWindow.table}.mcFit WHERE Kartennr = '{Kartennr}'", 5);

            tbZurNachname.Text = result.First().Split(';')[0];
            tbZurVorname.Text = result.First().Split(';')[1];
            tbZurAbteilung.Text = result.First().Split(';')[2];
            tbZurHandy.Text = result.First().Split(';')[3];
            tbZurEmail.Text = result.First().Split(';')[4];
        }

        private async void btnAusgebenUnterschrift_Click(object sender, RoutedEventArgs e)
        {
            var name = tbAusVorname.Text + "  " + tbAusNachname.Text;

            if (signoPad._stPad.DeviceGetCount() > 0)
            {

                if (tbAusVorname.Text != "" &&
                    tbAusNachname.Text != "" &&
                    tbAusAbteilung.Text != "" &&
                    tbAusHandy.Text != "" &&
                    tbAusEmail.Text != "")
                {
                    var sig = new Signature(Signature.DisclaimerType.McFit, name, tbAusAbteilung.Text, tbAusHandy.Text);

                    if (sig.ShowDialog() == false)
                    {
                        _signature = sig.ResultByte;

                        if (_signature != null)
                        {
                            int Kartennr = Convert.ToInt32(cBAusKarte.SelectedValue.ToString().Split(' ')[2]);


                            //await SQL.WriteSQL($"UPDATE {MainWindow.table}.mcFit SET Vorname = '{tbAusVorname.Text}', Nachname = '{tbAusNachname.Text}', Abteilung = '{tbAusAbteilung.Text}', Handynr = '{tbAusHandy.Text}', Email = '{tbAusEmail.Text}', AusgabeTimestamp = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', ZurueckTimestamp = null, AktuellAusgegeben = '1', Signature = @signature, AusgegebenDruch = '{Environment.UserName}' WHERE Kartennr = '{Kartennr}'", _signature);
                            var cmd = SQL.CreateAndReturnSQLCommand($"UPDATE {MainWindow.table}.mcFit SET Vorname = @tbAusVorname, Nachname = @tbAusNachname, Abteilung = @tbAusAbteilung, Handynr = @tbAusHandy, Email = @tbAusEmail, AusgabeTimestamp = @DateTime, ZurueckTimestamp = null, AktuellAusgegeben = '1', Signature = @signature, AusgegebenDurch = @UserName WHERE Kartennr = @Kartennr", new List<MySqlParameter>()
                                                        {
                                                            new MySqlParameter("@tbAusVorname", tbAusVorname.Text),
                                                            new MySqlParameter("@tbAusNachname", tbAusNachname.Text),
                                                            new MySqlParameter("@tbAusAbteilung", tbAusAbteilung.Text),
                                                            new MySqlParameter("@tbAusHandy", tbAusHandy.Text),
                                                            new MySqlParameter("@tbAusEmail", tbAusEmail.Text),
                                                            new MySqlParameter("@DateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                                            new MySqlParameter("@UserName", Environment.UserName),
                                                            new MySqlParameter("@Kartennr", Kartennr)
                                                        });

                            await SQL.CreateAndWriteSQLwithSignature(cmd, _signature);


                            await Query(CardType.McFit);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Karte auswählen und alle Felder ausfüllen!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
                MessageBox.Show("Kein Unterschriftenpad gefunden\nMeldung 0x01", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);


        }

        private async void btnZuruecknehmen_Click(object sender, RoutedEventArgs e)
        {
            int Kartennr = Convert.ToInt32(cBZurKarte.SelectedValue.ToString().Split(' ')[2]);

            //await SQL.WriteSQL($"UPDATE {MainWindow.table}.mcFit SET ZurueckTimestamp = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', AktuellAusgegeben = '0' WHERE Kartennr = '{Kartennr}'");
            await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.mcFit SET ZurueckTimestamp = @DateTime, AktuellAusgegeben = '0' WHERE Kartennr = @Kartennr", new List<MySqlParameter>()
                                        {
                                            new MySqlParameter("@DateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                                            new MySqlParameter("@Kartennr", Kartennr)
                                        });




            await Query(CardType.McFit);
        }

        private void btnSignature_Click(object sender, RoutedEventArgs e)
        {
            var signBtn = ((sender as Button).DataContext) as System.Data.DataRowView;

            var i = SQL.ReadSingleByteArr($"SELECT Signature FROM {MainWindow.table}.mcFit WHERE Kartennr = '{(signBtn).Row.ItemArray[0].ToString()}'");
            BitmapImage image = null;

            if (i != null)
                image = Helper.ConvertBitmapToImage(i);
            else
                image = new BitmapImage(new Uri(@"/Resources/NoSignature.png", UriKind.Relative));

            var iv = new ImageView(image);
            iv.Owner = this;
            iv.ShowDialog();
        }

        private void GruenRot_Click(object sender, RoutedEventArgs e)
        {
            tabcontrol.SelectedIndex = 0;
        }

        private void McFit_Click(object sender, RoutedEventArgs e)
        {
            tabcontrol.SelectedIndex = 1;
        }

        private void tabcontrol_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch(tabcontrol.SelectedIndex)
            {
                case 0:
                    btnMcFit.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x25, 0x2F, 0x3B));
                    btnGreenRed.Background = new LinearGradientBrush(Color.FromArgb(0xFF, 0x25, 0x2F, 0x3B), Color.FromArgb(0xFF, 0x1B, 0x55, 0x7B), 90);
                    break;
                case 1:
                    btnGreenRed.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x25, 0x2F, 0x3B));
                    btnMcFit.Background = new LinearGradientBrush(Color.FromArgb(0xFF, 0x25, 0x2F, 0x3B), Color.FromArgb(0xFF, 0x1B, 0x55, 0x7B), 90);
                    break;
            }
        }



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

            await Query(CardType.All);

            CheckAllBoxes(true);

            gridSpinner.Visibility = Visibility.Collapsed;
        }

        private async Task Query(CardType type)
        {
            await Task.Run(() =>
            {
                if (type == CardType.DB || type == CardType.All) karten = SQL.ReadSQL($"SELECT `kartennr`,`farbe`,`benutzer`,`telnr`,`AusgegebenDurch`,`AusgegebenTimestamp`,`AusgegebenAnFirma`,`AusgegebenAnPerson` FROM {MainWindow.table}.karten ORDER BY AusgegebenTimestamp DESC", karten).Result;

                if (type == CardType.McFit || type == CardType.All) mcFit = SQL.ReadSQL($"SELECT `Kartennr`,`Vorname`,`Nachname`,`Abteilung`,`Handynr`,`Email`,`AusgabeTimestamp`,`ZurueckTimestamp`,`AktuellAusgegeben` FROM {MainWindow.table}.mcFit ORDER BY AusgabeTimestamp", mcFit).Result;
            });

            if (type == CardType.DB || type == CardType.All)
            {
                if (!karten.Columns.Contains("IsChecked"))
                    karten.Columns.Add("IsChecked", typeof(bool));

                dgCards.DataContext = karten;
            }
            if (type == CardType.McFit || type == CardType.All) dgMcFit.DataContext = mcFit;
        }

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

        public enum CardType
        {
            All,
            DB,
            McFit
        }
    }
}
