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;
using sql_pagining.models;
using Dapper;
using MySqlConnector;
using System.ComponentModel;
using Microsoft.Win32;

namespace sql_pagining.Windows
{
    public partial class EditProductWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void Invalidate()
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("currentProduct"));
        }
        public Visibility DeleteProductVisibly
        {
            get
            {
                if (currentProduct != null)
                {
                    return currentProduct.ID == 0 ? Visibility.Collapsed : Visibility.Visible;
                }
                else
                {
                    return Visibility.Collapsed;
                }
            }
        }
        public Product currentProduct { get; set; }
        public List<ProductType> productTypeList { get; set; }
        public int selectedProductIndex { get; set; } = -1;
        public void saveProduct(Product product)
        {
            using (MySqlConnection db = new MySqlConnection(connectionString))
            {
                if (product.ID == 0)
                {
                    using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Product (ProductTypeID, Title, ArticleNumber, Description, Image, ProductionPersonCount, ProductionWorkshopNumber, MinCostForAgent) " +
                        "VALUES (@ProductTypeID, @Title, @ArticleNumber, @Description, @Image, @ProductionPersonCount, @ProductionWorkshopNumber, @MinCostForAgent)", db))
                    {
                        cmd.Parameters.AddWithValue("@ProductTypeID", product.ProductTypeID);
                        cmd.Parameters.AddWithValue("@Title", product.Title);
                        cmd.Parameters.AddWithValue("@ArticleNumber", product.ArticleNumber);
                        cmd.Parameters.AddWithValue("@Description", product.Description);
                        cmd.Parameters.AddWithValue("@Image", product.Image);
                        cmd.Parameters.AddWithValue("@ProductionPersonCount", product.ProductionPersonCount);
                        cmd.Parameters.AddWithValue("@ProductionWorkshopNumber", product.ProductionWorkshopNumber);
                        cmd.Parameters.AddWithValue("@MinCostForAgent", product.MinCostForAgent);

                        db.Open();
                        cmd.ExecuteNonQuery();
                        product.ID = (int)cmd.LastInsertedId;
                        db.Close();
                    }
                }
                else
                {
                    db.Execute("UPDATE Product SET Title=@Title, ProductTypeID=@ProductTypeID, " +
                        "ArticleNumber=@ArticleNumber, Description=@Description, " +
                        "Image=@Image, ProductionPersonCount=@ProductionPersonCount, " +
                        "ProductionWorkshopNumber=@ProductionWorkshopNumber, " +
                        "MinCostForAgent=@MinCostForAgent " +
                        "WHERE ID=@ID", product);
                }
            }
        }
        public EditProductWindow(Product editWindow)
        {
            InitializeComponent();
            DataContext = this;
            currentProduct = editWindow;
            if (currentProduct != null)
            {
                root.Title = currentProduct.ID == 0 ? "Новый продукт" : "Редактирование продукта";
                productTypeList = Globals.dataProvider.getProductTypes().ToList();
                if (currentProduct.ID > 0)
                {
                    selectedProductIndex = productTypeList.FindIndex(pt => pt.ID == currentProduct.ProductTypeID);
                }
            }
            else
            {
                MessageBox.Show("Продукт не был передан.");
            }
        }
        public static class DBDataProvider
        {
            public static string connectionString = "Server=kolei.ru; User ID=sbahtina; Password=010906; Database=sbahtina";
        }
        private void ChangeImage_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();
            }
        }
        private string connectionString;
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ProductTypeComboBox.SelectedItem != null)
                {
                    currentProduct.ProductTypeID = ((ProductType)ProductTypeComboBox.SelectedItem).ID;
                }
                else
                {
                    throw new Exception("Не выбран тип продукта");
                }

                if (!ValidatePrice(currentProduct.Price))
                {
                    throw new Exception("Некорректная стоимость продукта. Допустимо не более двух знаков после запятой и положительное число.");
                }

                if (!ValidateArticle(currentProduct.ArticleNumber, currentProduct.ID))
                {
                    throw new Exception("Артикул уже существует.");
                }

                Globals.dataProvider.saveProduct(currentProduct);
                DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool ValidatePrice(decimal price)
        {
            return price >= 0 && Math.Round(price, 2) == price;
        }

        private bool ValidateArticle(string article, int productId)
        {
            return Globals.dataProvider.GetProductByArticle(article)?.ID != productId;
        }


        private void DeleteProductButton_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.removePriceHistory(currentProduct.ID);

                Globals.dataProvider.removeProduct(currentProduct.ID);
                DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void ProductTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ProductTypeComboBox.SelectedItem != null)
            {
                currentProduct.ProductTypeID = ((ProductType)ProductTypeComboBox.SelectedItem).ID;
            }
        }

    }
}
