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;
using BuechermarktClient.Models;
using System.Threading;
using MongoDB.Driver;

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

      public BookTypes()
      {
         InitializeComponent();
         RefreshThread = new Thread(RefreshThreadS);
         RefreshThread.Start();
         RefreshThread.IsBackground = true;
         Closing += BookTypes_Closing;
      }

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

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

      public void LoadList()
      {
         var list = MainWindow.BookTypeCollection.FindSync((b)=>true).ToList();
         Dispatcher.BeginInvoke(new Action(delegate (){
            BookTypesList.ItemsSource = list;
         }));
      }

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

      private void ListViewItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
      {
         var item = sender as ListViewItem;
         if (item != null && item.IsSelected)
         {
            var editWindow = new BookTypesEdit(item.DataContext as BookType) {
               Owner = this
            };
            editWindow.Show();
         }
      }
   }
}
