using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MongoDB.Driver;
using System.Windows.Data;
using System.Globalization;
using MongoDB.Bson;
using System.Collections.Generic;
using System.ComponentModel;

namespace BuechermarktClient
{
   [ValueConversion(typeof(object), typeof(string))]
   public class EnumConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         return value?.ToString();
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

   [ValueConversion(typeof(object), typeof(string))]
   public class StudentConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         var i = MainWindow.StudentCollection.Find(s => s.ID == (ObjectId)value).FirstOrDefault();
         if (i == null) return value;
         return i.Lastname + ", " + i.Forname;
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

   [ValueConversion(typeof(object), typeof(string))]
   public class BookTypeConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         var i = MainWindow.BookTypeCollection.Find(bt => bt.ID == (ObjectId)value).FirstOrDefault();
         if (i == null) return value;
         return i.Name;
      }

      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

   /// <summary>
   /// Interaktionslogik für Books.xaml
   /// </summary>
   public partial class Books : Window, INotifyPropertyChanged
   {
      public Thread RefreshThread = null;
      private bool ThreadRunning = true;

      public event PropertyChangedEventHandler PropertyChanged;
      protected void OnPropertyChanged(string propertyName)
      {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }

      private string _SearchField;
      public string SearchField
      {
         get
         {
            return _SearchField;
         }
         set
         {
            if (value != _SearchField)
            {
               _SearchField = value;
               OnPropertyChanged("SearchField");
            }
         }
      }

      public Books()
      {
         InitializeComponent();
         RefreshThread = new Thread(RefreshThreadS);
         RefreshThread.Start();
         RefreshThread.IsBackground = true;
         Closing += Book_Closing;
         DataContext = this;
      }

      private void Book_Closing(object sender, System.ComponentModel.CancelEventArgs e)
      {
         ThreadRunning = false;
      }

      public void RefreshThreadS()
      {
         while (ThreadRunning)
         {
            LoadList();
            Thread.Sleep(5000);
         }
      }

      public void LoadList()
      {

         List<Models.Book> list = null;
         var not = true;
         while (not)
         {
            try
            {
               list = MainWindow.BookCollection.FindSync((b) => true).ToList();
               not = false;
            } catch (MongoExecutionTimeoutException)
            {
               Thread.Sleep(200);
            }
         }

         var show = new List<Models.Book>();
         if (SearchField != null && SearchField != String.Empty)
         {
            if (SearchField == "%d%")
            {
               foreach (var e in list)
               {
                  foreach (var e2 in list)
                  {
                     if (e.ID == e2.ID) continue;
                     if (e.LabelId == e2.LabelId) show.Add(e);
                  }
               }
            }
            else
            {
               foreach (var e in list)
               {
                  if (e.LabelId.ToLower().Contains(SearchField.ToLower()) || e.Price.ToString().ToLower().Contains(SearchField.ToLower()) || e.Student.ToString().ToLower().Contains(SearchField.ToLower()) || e.BookType.ToString().ToLower().Contains(SearchField.ToLower()) || e.State.ToString().ToLower().Contains(SearchField.ToLower()))
                  {
                     show.Add(e);
                  }
               }
            }
         }
         else
         {
            if(list.Count > 100)
            {
               for(int i = 0; i < 100; i++)
               {
                  show.Add(list[i]);
               }
            } else
            {
               show = list;
            }
         }
         Dispatcher.BeginInvoke(new Action(delegate () {
            BooksList.ItemsSource = show;
         }));
      }

      private void AddNew_Click(object sender, RoutedEventArgs e)
      {
         var editWindow = new BooksEdit(null)
         {
            Owner = this
         };
         editWindow.Show();
      }

      private void ListViewItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
      {
         if (sender is ListViewItem item && item.IsSelected)
         {
            var editWindow = new BooksEdit(item.DataContext as Models.Book)
            {
               Owner = this
            };
            editWindow.Show();
         }
      }

      private void Search_Click(object sender, RoutedEventArgs e)
      {
         LoadList();
      }
   }
}
