using mysql_connector2.res;
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;

namespace mysql_connector2.Windows
{
    public partial class AddMaterial : Window
    {
        private ProductMaterial _productMaterial;
        public List<Material> allMaterials { get; }
        public AddMaterial(ProductMaterial productMaterial)
        {
            InitializeComponent();
            DataContext = this;
            _productMaterial = productMaterial;

            allMaterials = new List<Material>(Globals.dataProvider.getAvailableMaterials().ToList());

            MaterialComboBox.ItemsSource = allMaterials;
            MaterialComboBox.DisplayMemberPath = "Title";
            MaterialComboBox.SelectedValuePath = "ID";
        }
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string searchText = SearchTextBox.Text.ToLower();

            var filteredMaterials = allMaterials
                .Where(m => m.Title.ToLower().Contains(searchText))
                .ToList();

            MaterialComboBox.ItemsSource = filteredMaterials;
            MaterialComboBox.IsDropDownOpen = true;
        }
        private void AddMaterialButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MaterialComboBox.SelectedItem == null)
                {
                    throw new Exception("Необходимо выбрать материал.");
                }

                if (!int.TryParse(MaterialCountTextBox.Text, out int count) || count <= 0)
                {
                    throw new Exception("Введите корректное количество.");
                }

                _productMaterial.MaterialID = (int)MaterialComboBox.SelectedValue;
                _productMaterial.Count = count;

                Globals.dataProvider.addProductMaterial(_productMaterial);

                DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}
