using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
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 ImageView.xaml
    /// </summary>
    public partial class ImageView : MetroWindow
    {
        Categories category = Categories.Zutritte;


        enum Categories
        {
            Zutritte,
            Karten,
            McFit
        }


        BitmapImage _image = null;
        bool _showComboBox = false;

        public ImageView(BitmapImage image, bool showComboBox = false)
        {
            _image = image;
            _showComboBox = showComboBox;

            InitializeComponent();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            await Task.Run(() => Init(_image, _showComboBox));

            dPDate.SelectedDate = DateTime.Now;

            cBSignature.SelectionChanged += cBSignature_SelectionChanged;
            cbOnlyWithSignature.Unchecked += cbOnlyWithSignature_Unchecked;
            cbOnlyWithSignature.Checked += cbOnlyWithSignature_Checked;
            dPDate.SelectedDateChanged += DatePicker_SelectedDateChanged;

            Helper.CheckWindowIsInScreenSpace(this);
        }

        private async void Init(BitmapImage image, bool showComboBox = false)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                if (!showComboBox) { dPDate.Visibility = cBSignature.Visibility = btnToday.Visibility = btnUp.Visibility = btnDown.Visibility = tbFilter.Visibility = lblFilter.Visibility = btnFiltern.Visibility = cbOnlyWithSignature.Visibility = Visibility.Collapsed; }
                else { cBSignature.Visibility = dPDate.Visibility = btnToday.Visibility = btnUp.Visibility = btnDown.Visibility = tbFilter.Visibility = lblFilter.Visibility = btnFiltern.Visibility = cbOnlyWithSignature.Visibility = Visibility.Visible; }
            }));

            if (image != null)
                Dispatcher.Invoke(new Action(() =>
                {
                    imageSignature.Source = image;
                }));
            else
            {
                //var list = await SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog");
                //list = list.OrderByDescending(p => p).ToList();


                Dispatcher.Invoke(new Action(() =>
                {
                    //cBSignature.ItemsSource = list;

                    gridSpinner.Visibility = Visibility.Collapsed;
                }));
            }            
        }

        private void cBSignature_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (category)
            {
                case Categories.Zutritte:
                    if (cBSignature.SelectedItem != null && cBSignature.SelectedIndex != -1)
                    {
                        var i = SQL.ReadSingleByteArr($"SELECT signature_blob FROM {MainWindow.table}.zutritteLog WHERE Name = '{cBSignature.SelectedItem.ToString().Split(';')[1]}' AND Zutritt = '{cBSignature.SelectedItem.ToString().Split(';')[0]}'");


                        if (i != null)
                            imageSignature.Source = Helper.ConvertBitmapToImage(i);
                        else
                            imageSignature.Source = new BitmapImage(new Uri(@"/Resources/NoSignature.png", UriKind.Relative));
                        //MessageBox.Show(this, "Keine Unterschrift vorhanden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    break;
                case Categories.Karten:
                    if (cBSignature.SelectedItem != null && cBSignature.SelectedIndex != -1)
                    {
                        var i = SQL.ReadSingleByteArr($"SELECT Signature FROM {MainWindow.table}.kartenLog WHERE benutzer = '{cBSignature.SelectedItem.ToString().Split(';')[1]}' AND AusgegebenTimestamp = '{cBSignature.SelectedItem.ToString().Split(';')[0]}'");


                        if (i != null)
                            imageSignature.Source = Helper.ConvertBitmapToImage(i);
                        else
                            imageSignature.Source = new BitmapImage(new Uri(@"/Resources/NoSignature.png", UriKind.Relative));
                        //MessageBox.Show(this, "Keine Unterschrift vorhanden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    break;
                case Categories.McFit:
                    if (cBSignature.SelectedItem != null && cBSignature.SelectedIndex != -1)
                    {
                        var i = SQL.ReadSingleByteArr($"SELECT Signature FROM {MainWindow.table}.mcFitLog WHERE Nachname = '{cBSignature.SelectedItem.ToString().Split(';')[1]}' AND AusgabeTimestamp = '{cBSignature.SelectedItem.ToString().Split(';')[0]}'");


                        if (i != null)
                            imageSignature.Source = Helper.ConvertBitmapToImage(i);
                        else
                            imageSignature.Source = new BitmapImage(new Uri(@"/Resources/NoSignature.png", UriKind.Relative));
                        //MessageBox.Show(this, "Keine Unterschrift vorhanden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    break;
            }

        }

        private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dPDate.SelectedDate.HasValue)
            {
                if (dPDate.SelectedDate.Value >= DateTime.Now.Date) btnUp.IsEnabled = false;
                else if (dPDate.SelectedDate.Value < DateTime.Now.Date) btnUp.IsEnabled = true;
            }

            Filtern();
        }

        private void btnToday_Click(object sender, RoutedEventArgs e)
        {
            dPDate.SelectedDate = DateTime.Now;
        }

        private void btnDown_Click(object sender, RoutedEventArgs e)
        {
            if (dPDate.SelectedDate.HasValue) dPDate.SelectedDate = dPDate.SelectedDate.Value - TimeSpan.FromDays(1);
            else dPDate.SelectedDate = DateTime.Now;
        }

        private void btnUp_Click(object sender, RoutedEventArgs e)
        {
            if (dPDate.SelectedDate.HasValue && dPDate.SelectedDate.Value < DateTime.Now.Date) dPDate.SelectedDate = dPDate.SelectedDate.Value + TimeSpan.FromDays(1);
            else dPDate.SelectedDate = DateTime.Now;
        }

        private void btnFiltern_Click(object sender, RoutedEventArgs e)
        {
            Filtern();
        }

        private void tbFilter_PreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            lblFilter.Visibility = Visibility.Hidden;
        }

        private void tbFilter_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbFilter.Text)) lblFilter.Visibility = Visibility.Visible;
        }

        private void tbFilter_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
                Filtern();
        }

        private void Filtern()
        {
            switch (category)
            {
                case Categories.Zutritte:
                    FilterZutritte();
                    break;
                case Categories.Karten:
                    FilterKarten();
                    break;
                case Categories.McFit:
                    FilterMcFit();
                    break;
            }

            if (cBSignature.Items.Count == 0) cBSignature.ItemsSource = new List<string>() { "Keine Einträge gefunden..." };

            //cBSignature.IsDropDownOpen = false;
            //cBSignature.IsDropDownOpen = true;
        }

        private void FilterZutritte()
        {
            string withSign = "";
            if (cbOnlyWithSignature.IsChecked.Value) withSign = " AND signature_blob IS NOT NULL";

            if (dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog WHERE Zutritt LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%' AND Name LIKE '%{tbFilter.Text}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (!dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog WHERE Name LIKE '%{tbFilter.Text}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog WHERE Zutritt LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (!dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                if (cbOnlyWithSignature.IsChecked.Value) withSign = " WHERE signature_blob IS NOT NULL";
                cbOnlyWithSignature.IsChecked = false;
                var list = SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
        }

        private void FilterKarten()
        {
            //throw new NotImplementedException();
            string withSign = "";
            if (cbOnlyWithSignature.IsChecked.Value) withSign = " AND Signature IS NOT NULL";

            if (dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgegebenTimestamp,benutzer FROM {MainWindow.table}.kartenLog WHERE AusgegebenTimestamp LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%' AND Name LIKE '%{tbFilter.Text}%'{withSign} ORDER BY AusgegebenTimestamp").Result;

                cBSignature.ItemsSource = list;
            }
            else if (!dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgegebenTimestamp,benutzer FROM {MainWindow.table}.kartenLog WHERE benutzer LIKE '%{tbFilter.Text}%'{withSign} ORDER BY AusgegebenTimestamp").Result;

                cBSignature.ItemsSource = list;
            }
            else if (dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgegebenTimestamp,benutzer FROM {MainWindow.table}.kartenLog WHERE AusgegebenTimestamp LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%'{withSign} ORDER BY AusgegebenTimestamp").Result;

                cBSignature.ItemsSource = list;
            }
            else if (!dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                if (cbOnlyWithSignature.IsChecked.Value) withSign = " WHERE Signature IS NOT NULL";
                cbOnlyWithSignature.IsChecked = false;
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgegebenTimestamp,benutzer FROM {MainWindow.table}.kartenLog{withSign} ORDER BY AusgegebenTimestamp").Result;

                cBSignature.ItemsSource = list;
            }
        }

        private void FilterMcFit()
        {

            string withSign = "";
            if (cbOnlyWithSignature.IsChecked.Value) withSign = " AND signature_blob IS NOT NULL";

            if (dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgabeTimestamp,Nachname FROM {MainWindow.table}.mcFitLog WHERE AusgabeTimestamp LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%' AND Name LIKE '%{tbFilter.Text}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (!dPDate.SelectedDate.HasValue && !string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgabeTimestamp,Nachname FROM {MainWindow.table}.mcFitLog WHERE Nachname LIKE '%{tbFilter.Text}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgabeTimestamp,Nachname FROM {MainWindow.table}.mcFitLog WHERE AusgabeTimestamp LIKE '%{(dPDate).SelectedDate.Value.ToString("yyyy-MM-dd")}%'{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
            else if (!dPDate.SelectedDate.HasValue && string.IsNullOrWhiteSpace(tbFilter.Text))
            {
                if (cbOnlyWithSignature.IsChecked.Value) withSign = " WHERE Signature IS NOT NULL";
                cbOnlyWithSignature.IsChecked = false;
                var list = SQL.ReadDateTimeAndStringList($"SELECT AusgabeTimestamp,Nachname FROM {MainWindow.table}.mcFitLog{withSign}").Result;

                cBSignature.ItemsSource = list.OrderByDescending(p => p);
            }
        }

        private void cbOnlyWithSignature_Unchecked(object sender, RoutedEventArgs e)
        {
            Filtern();
        }

        private void cbOnlyWithSignature_Checked(object sender, RoutedEventArgs e)
        {
            Filtern();
        }

        private void dPDate_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
        {
            MessageBox.Show("Kein gültiges Datumsformat in Feld 'Datum'", "Fehler", MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        private async void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            List<string> list = new List<string>();
            var cont = (sender as RadioButton).Content;

            await Task.Run(async () =>
            {
                switch (cont)
                {
                    case "Zutritte":
                        category = Categories.Zutritte;
                        list = await SQL.ReadDateTimeAndStringList($"SELECT Zutritt,Name FROM {MainWindow.table}.zutritteLog WHERE Zutritt IS NOT NULL");
                        list = list.OrderByDescending(p => p).ToList();
                        break;

                    case "Karten":
                        category = Categories.Karten;
                        list = await SQL.ReadDateTimeAndStringList($"SELECT AusgegebenTimestamp,benutzer FROM {MainWindow.table}.kartenLog WHERE AusgegebenTimestamp IS NOT NULL");
                        list = list.OrderByDescending(p => p).ToList();
                        break;

                    case "McFit":
                        category = Categories.McFit;
                        list = await SQL.ReadDateTimeAndStringList($"SELECT AusgabeTimestamp,Nachname FROM {MainWindow.table}.mcFitLog WHERE AusgabeTimestamp IS NOT NULL");
                        list = list.OrderByDescending(p => p).ToList();
                        break;
                }
            });

            Dispatcher.Invoke(new Action(() =>
            {
                if (cBSignature != null)
                {
                    cBSignature.ItemsSource = list;
                    gridSpinner.Visibility = Visibility.Collapsed;
                }

            }));
        }


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