using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace BookStore
{
    public partial class MainWindow : Window
    {

            private BookStoreContext _context;
            public MainWindow()
            {
                InitializeComponent();
                _context = new BookStoreContext();
                Load();
            }

            private void Load()
            {
                BooksGrid.ItemsSource = _context.Books.ToList();
            }

            private void BtnInsert_Click(object sender, RoutedEventArgs e)
            {
                if (!decimal.TryParse(TbPrice.Text, out decimal price))
                {
                    return;
                }

                Book book = new()
                {
                    Name = TbName.Text,
                    Price = price,
                    Autor = TbAutor.Text,
                    Category = TbCategory.Text,
                };

            _context.Books.Add(book);
            _context.SaveChanges();
            Load();
            }
             private void BtnDelete_Click(object sender, RoutedEventArgs e)
             {
                 if (BooksGrid.SelectedItem is Book selectedBook)
                 {
                        _context.Books.Remove(selectedBook);
                        _context.SaveChanges();
                        Load();
                 }
             }

            private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (BooksGrid.SelectedItem is Book selectedBook)
                {
                    TbName.Text = selectedBook.Name;
                    TbPrice.Text = selectedBook.Price.ToString();
                    TbAutor.Text = selectedBook.Autor;
                    TbCategory.Text = selectedBook.Category;
                }
            }

        private void BtnUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (BooksGrid.SelectedItem is Book selectedBook)
            {
                if (!decimal.TryParse(TbPrice.Text, out decimal price))
                {
                    return;
                }
                selectedBook.Name = TbName.Text;
                selectedBook.Price = price;
                selectedBook.Autor = TbAutor.Text;
                selectedBook.Category = TbCategory.Text;
                _context.SaveChanges();
                Load();
            }
        }


    }
}
