using Avalonia;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using System.Reflection;
using System;
using Agents.Models;
using System.Collections.ObjectModel;
using Avalonia.Interactivity;
using System.Linq;
using System.Runtime.ExceptionServices;

namespace Agents
{
    public partial class MainWindow : Window
    {
        static User11Context db = new User11Context();
        ObservableCollection<Agent> AgentsitemSource = new ObservableCollection<Agent>(db.Agents.OrderBy(it=>it.Title));
        public MainWindow()
        {
            InitializeComponent();
            ListAgents.ItemsSource = AgentsitemSource;
        }
        private void ListBox_SelectionChanged(object? sender, Avalonia.Controls.SelectionChangedEventArgs e)
        {
            if(sender != null)
            {
                using (User11Context db = new User11Context())
                {
                    try
                    {
                        UpdateInfo();
                    }
                    catch (Exception ex)
                    {
                        ExceptionDispatchInfo.Capture(ex).Throw();
                    }
                }
            }
        }
        private void ListBox_SelectionChanged1(object? sender, Avalonia.Controls.SelectionChangedEventArgs e)
        {
            if (sender != null)
            {

            }
        }

        private void ButtonUpdate(object sender, RoutedEventArgs e)
        {
            UpdateInfo();
        }

        private void UpdateInfo()
        {
            Agent agent = db.Agents.Where(it => it == ListAgents.SelectedItem).FirstOrDefault();
            Productsale? PS = db.Productsales.Where(it => it.Agentid == agent.Id).FirstOrDefault();
            if (PS != null)
            {
                var prods = db.Productsales
                .Where(PWS => PWS.Agentid == agent.Id)
                .Select(PWS => new Product
                {
                    Title = PWS.Product.Title,
                    Image = PWS.Product.Image,
                    Producttypeid = PWS.Product.Producttypeid,
                    Productionpersoncount = PWS.Product.Productionpersoncount,
                    Productionworkshopnumber = PWS.Product.Productionworkshopnumber,
                    Mincostforagent = PWS.Product.Mincostforagent,
                    Description = PWS.Product.Description,
                    Articlenumber = PWS.Product.Articlenumber
                }).ToList();

                switch (SortListAgents.SelectedIndex)
                {
                    case 1: prods = prods.OrderBy(p => p.Title).ToList(); break;
                    case 2: prods = prods.OrderByDescending(p => p.Title).ToList(); break;
                    default: break;
                }

                ListProducts.ItemsSource = new ObservableCollection<Product>(prods);
            }
        }
    }
}