using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Interactivity;
using demko_term.Models;
using Microsoft.EntityFrameworkCore;

namespace demko_term;

public partial class HistoryWindow : Window
{
    private ObservableCollection<HistoryPresenter> history = new();
    private List<HistoryPresenter> dataSourceHistory;

    public HistoryWindow()
    {
        InitializeComponent();
        DataContext = this;
        using var context = new DemoCourseworkContext();
        dataSourceHistory = context.EmployeesHistories
            .Include(h => h.Employee)
            .Select(h => new HistoryPresenter
            {
                Login = h.Employee.Login,
                LastLogin = h.LastLogin,
                SuccessLoginBool = h.SuccessLogin
            })
            .ToList();

        LoginComboBox.ItemsSource = dataSourceHistory.Select(it => it.Login).Distinct().ToList();
        DateComboBox.ItemsSource = dataSourceHistory.Select(it => it.LastLogin).Where(it => it.HasValue).Distinct().ToList();
        
        HistoryListBox.ItemsSource = history;
        DisplayServices();
    }

    public class HistoryPresenter
    {
        public string Login { get; set; } = string.Empty;
        public DateTime? LastLogin { get; set; }
        public bool? SuccessLoginBool { get; set; }
        
        public string SuccessLogin => SuccessLoginBool.HasValue ? (SuccessLoginBool.Value ? "Успешно" : "Не успешно") : "";
    }

    private void DisplayServices()
    {
        var temp = dataSourceHistory;

        if (LoginComboBox.SelectedItem is string selectedLogin)
        {
            temp = temp
                .Where(it => it.Login == selectedLogin)
                .ToList();
        }

        if (DateComboBox.SelectedItem is DateTime selectedDate)
        {
            temp = temp
                .Where(it => it.LastLogin.HasValue && it.LastLogin.Value.Date == selectedDate.Date)
                .ToList();
        }

        history.Clear();
        foreach (var item in temp.OrderBy(it => it.LastLogin))
        {
            history.Add(item);
        }
    }

    public void LoginComboBox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayServices();
    }
    
    public void DateComboBox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayServices();
    }
}