using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using BuechermarktClient.Models;
using System.Threading;
using MongoDB.Driver;

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

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


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

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

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

      private void AddNew_Click(object sender, RoutedEventArgs e)
      {
         var editWindow = new StudentsEdit(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 StudentsEdit(item.DataContext as Student)
            {
               Owner = this
            };
            editWindow.Show();
         }
      }
   }
}
