using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using System.Text;
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;
using Dapper;
using MySqlConnector;
using wpf_connection3.model;
using wpf_connection3.Windows;

namespace wpf_connection3
{


    public partial class MainWindow : Window,
        INotifyPropertyChanged



    {

        private int _currentPage = 1;
        public int currentPage
        { get
            {
                return _currentPage;
            }

            set
            {
                _currentPage = value;
                Invalidate("productList");
            }
        }

        public List<string> pageList { get; set; } = new List<string>();
        private int productCount;


        public IEnumerable<Product> productList
        {
            get
            {
                switch (sortType)
                {
                    case 0:
                        Globals.dataProvider.setOrder("");
                        break;
                    case 1:
                        Globals.dataProvider.setOrder("Title");
                        break;
                    case 2:
                        Globals.dataProvider.setOrder("Title DESC");
                        break;
                    case 3:
                        Globals.dataProvider.setOrder("ProductionWorkshopNumber");
                        break;
                    case 4:
                        Globals.dataProvider.setOrder("ProductionWorkshopNumber DESC");
                        break;
                    case 5:
                        Globals.dataProvider.setOrder("MaterialCost");
                        break;
                    case 6:
                        Globals.dataProvider.setOrder("MaterialCost DESC");
                        break;
                }
                Globals.dataProvider.clearFilter();
                if (productTypeFilterId > 0)
                    Globals.dataProvider.addFilter(
                        "ProductTypeID = @ProductTypeID",
                        new { ProductTypeID = productTypeFilterId }
                    );
                if (searchFilter.Length > 0)
                {
                    Globals.dataProvider.addFilter(
                        //"(Title LIKE @search OR Description LIKE @search)",
                        "(Title LIKE @search)",
                        new { search = $"%{searchFilter}%" }
                    );
                }
                var result = Globals.dataProvider.getProduct(currentPage);
                productCount = Globals.dataProvider.getProductCount();
                pageList.Clear();
                pageList.Add("<");
                for (int i = 1; i < (productCount / Globals.PAGE_LEN) + 1; i++)
                {
                    pageList.Add(i.ToString());
                }
                pageList.Add(">");
                // PageListListBox.ItemsSource = pageList;
                Invalidate("pageList");
                return result;
            }

        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

        }
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            Globals.dataProvider = new ApiDataProvider();
            productTypeList = Globals.dataProvider.getProductTypes().ToList();
            productTypeList.Insert(0, new ProductType { Title = "Все типы продукции" });

        }
        public event PropertyChangedEventHandler? PropertyChanged;
        private void Invalidate(string element)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(element));
        }

        private void TextBlock_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            switch ((sender as TextBlock).Text)
            {
                case "<":
                    if (currentPage > 1) currentPage--;
                    return;

                case ">":
                    if (currentPage < productCount / Globals.PAGE_LEN) currentPage++;
                    return;

                default:
                    currentPage = Convert.ToInt32(
                        (sender as TextBlock).Text);
                    return;
            }
        }
        public string[] sortList { get; set; } =

        {
            "Без сортировки",
            "название по убыванию",
            "название по возрастанию",
            "номер цеха по убыванию",
            "номер цеха по возрастанию",
            "цена по убыванию",
            "цена по возрастанию"
        };
        private int sortType = 0;

        private void SortTypeComboBox_SelectionChanged(
            object? sender,
            SelectionChangedEventArgs e)
        {
            if (SortTypeComboBox != null)
            {
                sortType = SortTypeComboBox.SelectedIndex;
                Invalidate("productList");
            }
        }
        public List<ProductType> productTypeList { get; set; }
        private int productTypeFilterId = 0;

        private void ProductTypeFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // запоминаем ID выбранного типа
            productTypeFilterId = (ProductTypeFilter.SelectedItem as ProductType).ID;
            Invalidate("productList");
        }

        private string searchFilter = "";
        private void searchFilterTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (searchFilterTextBox.Text != null && searchFilterTextBox.Text != "")
            {
                searchFilter = searchFilterTextBox.Text;
                Invalidate("productList");
            }
        }
        public int productsSelectedCount = 0;
        private void ProductListBox_OnSelectionChanged(
            object? sender,
            SelectionChangedEventArgs e)
        {
            if (ProductListBox != null)
            {
                productsSelectedCount = ProductListBox.SelectedItems.Count;
                Invalidate("costChangeButtonVisible");
            }
        }
        public string costChangeButtonVisible
        {
            get
            {
                return productsSelectedCount > 1 ? "Visible" : "Hidden";
            }
        }

        private void CostChangeButton_Click(object sender, RoutedEventArgs e)
        {
            decimal sum = 0;
            List<int> idList = new List<int>();
            foreach (Product item in ProductListBox.SelectedItems)
            {
                sum += item.MinCostForAgent;
                idList.Add(item.ID);
            }

            // создаём окно, передавая ему среднюю цену    
            var newWindow = new EnterMinCostForAgentWindow(
                sum / ProductListBox.SelectedItems.Count);

            try
            {
                if ((bool)newWindow.ShowDialog())
                {
                    Globals.dataProvider.setMinCostForAgent(
                        newWindow.Result,
                        idList.ToArray());
                    Invalidate("productList");
                }
            }

            catch { MessageBox.Show("Чото не то"); }

        }
        private void ProductListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var clickedElement = e.OriginalSource as FrameworkElement;
            var product = clickedElement.DataContext as Product;
            var newEditWindow = new EditProductWindow(product);
            if ((bool)newEditWindow.ShowDialog())
            {
                Invalidate("ProductList");
            }
        }

        private void AddProductButton_Click(object sender, RoutedEventArgs e)
        {
            var newEditWindow = new EditProductWindow(new Product());
            if ((bool)newEditWindow.ShowDialog())
            {
                Invalidate("ProductList");
            }
        }
    }
    

}