using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
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;
using wpf_connection3.model;

namespace wpf_connection3.Windows
{

    public partial class EditProductWindow : Window, INotifyPropertyChanged
    {
        public int selectedProductIndex { get; set; } = -1;
        public List<ProductType> productTypeList { get; set; }
        public Product currentProduct { get; set; }
        public IEnumerable<ProductMaterial> productMaterialList
        {
            get
            {
                return Globals.dataProvider.getProductMaterials(currentProduct.ID);
            }
        }
        public EditProductWindow(Product editProduct)
        {
            InitializeComponent();
            DataContext = this;
            currentProduct = editProduct;
            root.Title = currentProduct.ID == 0 ? "Новый продукт" : "Редактирование продукта";
            productTypeList = Globals.dataProvider.getProductTypes().ToList();
            if (currentProduct.ID > 0)
            {
                selectedProductIndex = productTypeList.FindIndex(pt => pt.ID == currentProduct.ProductTypeID);

            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void Invalidate(string element)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs($"{element}"));
        }
        private void ChangeImageButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog GetImageDialog = new OpenFileDialog();
           
            GetImageDialog.Filter = "Файлы изображений: (*.png, *.jpg)|*.png;*.jpg";

            
            GetImageDialog.InitialDirectory = Environment.CurrentDirectory;
            if (GetImageDialog.ShowDialog() == true)
            {
                
                currentProduct.Image = GetImageDialog.FileName.Substring(Environment.CurrentDirectory.Length);
                                    
                Invalidate(currentProduct.Image);
            }
        }
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
               
                if (ProductTypeComboBox.SelectedIndex != null)
                {
                    currentProduct.ProductTypeID = ((ProductType)ProductTypeComboBox.SelectedItem).ID;
                }
                else
                {
                    throw new Exception("Не выбран тип продукта");
                }

                                decimal minCost = decimal.Parse(MinCostForAgentTextBox.Text, CultureInfo.InvariantCulture);
                int decIndex = minCost.ToString().IndexOf('.');
                if (minCost > 0 && (decIndex == -1 || minCost.ToString().Length - decIndex <= 2))
                {
                    currentProduct.MinCostForAgent = minCost;
                }
                else
                {
                    throw new Exception("Цена должна быть больше 0 с двумя знаками после точки");
                }

                              string newArticleNumber = ArticleNumberTextBox.Text;
                if (Globals.dataProvider.getArticleCheck(newArticleNumber, currentProduct.ID) == 0)
                {
                    currentProduct.ArticleNumber = newArticleNumber;
                }
                else
                {
                    throw new Exception("Данный артикул уже используется");
                }

                currentProduct.Title = TitleTextBox.Text;
                currentProduct.ProductionPersonCount = Convert.ToInt32(ProductionPersonCountTextBox.Text);
                currentProduct.ProductionWorkshopNumber = Convert.ToInt32(ProductionWorkshopNumberTextBox.Text);
                currentProduct.Description = DescriptionTextBox.Text;

                Globals.dataProvider.saveProduct(currentProduct);
                DialogResult = true;
            }

                  catch (FormatException)
            {
                MessageBox.Show("Используйте только цифры");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var saleCount = Globals.dataProvider.saleCount(currentProduct.ID);

                if (saleCount > 0)
                    throw new Exception("Нельзя удалять продукт с продажами");

                Globals.dataProvider.removeProductMaterial(currentProduct.ID);
                Globals.dataProvider.removeProductCostHistory(currentProduct.ID);
                Globals.dataProvider.removeProduct(currentProduct.ID);
                DialogResult = true;
                MessageBox.Show("Продукт удален");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void DeleteMaterialTextBox_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var productMaterial = (sender as TextBlock).Tag as ProductMaterial;
            Globals.dataProvider.deleteProductMaterial(productMaterial.MaterialId, productMaterial.ProductId);
            Invalidate("productMaterialList");
        }

        private void AddMaterialButton_Click(object sender, RoutedEventArgs e)
        {
            var EditWindow = new EditingMaterialWindow(currentProduct.ID);
            if ((bool)EditWindow.ShowDialog())
            {
                Invalidate("productMaterialList");
            }
        }

    }
}
