using BuechermarktClient.Models;
using MongoDB.Driver;
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace BuechermarktClient
{
   /// <summary>
   /// Interaktionslogik für BookTypesEdit.xaml
   /// </summary>
   public partial class BookTypesEdit : Window, INotifyPropertyChanged
   {
      private bool New = false;
      private BookType BookType = null;
      private string _Name;
      public string BName
      {
         get
         {
            return _Name;
         }
         set {
            if(value != _Name)
            {
               _Name = value;
               OnPropertyChanged("BName");
            }
         }
      }

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

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

      public BookTypesEdit(BookType booktype)
      {
         DataContext = this;
         InitializeComponent();
         if(booktype == null)
         {
            BookType = new BookType();
            New = true;
         } else
         {
            BookType = booktype;
            BName = booktype.Name;
            BISBN = booktype.ISBN;
         }
      }

      private void Save_Click(object sender, RoutedEventArgs e)
      {
         BookType.Name = BName;
         BookType.ISBN = BISBN;
         while (true)
         {
            try
            {
               if (New)
               {
                  MainWindow.BookTypeCollection.InsertOne(BookType);
               }
               else
               {
                  MainWindow.BookTypeCollection.FindOneAndUpdate(bt => bt.ID == BookType.ID, Builders<BookType>.Update.Set((bt) => bt.Name, BookType.Name).Set(bt => bt.ISBN, BookType.ISBN));
               }
               Close();
               return;
            } catch (MongoExecutionTimeoutException)
            {
               Thread.Sleep(100);
            }
         }
      }

      private void Delete_Click(object sender, RoutedEventArgs e)
      {
         while (true)
         {
            try
            {
               if (BookType.ID != null)
               {
                  MainWindow.BookTypeCollection.DeleteOne(bt => bt.ID == BookType.ID);
               }
               Close();
               return;
            } catch (MongoExecutionTimeoutException)
            {
               Thread.Sleep(100);
            }
         }
      }
   }
}
