using examPrepare.ViewModels;
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.Navigation;
using System.Windows.Shapes;

namespace examPrepare.Pages
{
  /// <summary>
  /// Interaction logic for Cart.xaml
  /// </summary>
  public partial class Cart : Page
  {
    public CartViewModel cartData = new CartViewModel();
    public Cart()
    {
      InitializeComponent();
      DataContext = cartData;
    }
    private void setProductCount(string id, int value)
    {
      if (value == 0)
      {
        GlobalInfo.cart.Remove(id);
        cartData.Products.RemoveAll(p => p.Id == id);
        GlobalInfo.setUpProductCountFunc();
        cartData.notifyChange();
        return;
      }
      GlobalInfo.cart[id] = value;
      cartData.Products.ForEach(x => {
        if (x.Id == id)
        {
          x.count = value;
        }
      });
      GlobalInfo.setUpProductCountFunc();
      cartData.notifyChange();
    }
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
      TextBox textBox = sender as TextBox;
      string id = textBox.Uid;
      if (textBox.Text == String.Empty)
      {
        setProductCount(id, 0); 
      } else
      {
        int value = Convert.ToInt32(textBox.Text);
        setProductCount(id, value);
      }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      Order order = new Order();
      order.OrderStatus = 1;
      order.OrderPickupPoint = 1;
      order.OrderCode = "321";
      order.OrderCreationDate = DateTime.Now;
      order.OrderDeliveryDate = DateTime.Now;
      // test
      GlobalInfo.conn.Order.Add(order);
      int rez = GlobalInfo.conn.SaveChanges();
      MessageBox.Show(rez.ToString());
    }
  }
}
