using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Hard_Demo.Models;

namespace Hard_Demo;

public partial class EnterHistoryWindow : Window
{
    private ObservableCollection<LastEnter> lastEnter = new();
    public List<LastEnter> dataLastEnter;
    public bool sort = true;
    public EnterHistoryWindow()
    {
        InitializeComponent();
        using var context = new User2Context();


        dataLastEnter = context.LastEnters.Select(it => new LastEnter
        {
            EmployeId = it.EmployeId,
            EnterDatetime = it.EnterDatetime,
            EnterType = it.EnterType,
            Login = it.Login
        }).ToList();
        
        foreach (var newlastEnter in dataLastEnter)
        {
            lastEnter.Add(newlastEnter);
        }
        lastEnters.ItemsSource = lastEnter;
        LoginComboBox.ItemsSource = dataLastEnter.Select(it => it.Login);
        SortLogin();
    }

    private void SortLogin()
    {
        var temp = dataLastEnter;
        if (LoginComboBox.SelectedItem is String login)
        {
            temp = temp.Where(it => it.Login == login).ToList();
        }
        temp=sort ? temp.OrderBy(it => it.Login).ToList() : temp.OrderByDescending(it => it.Login).ToList();
        
        lastEnter.Clear();
        foreach (var userlogin in temp)
        {
            lastEnter.Add(userlogin);
        }
    }

    private void LoginComboBox_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        sort=!sort;
        SortLogin();
    }

    private void Button_Asc(object? sender, RoutedEventArgs e)
    {
        var sortedList = dataLastEnter.OrderBy(it => it.EnterDatetime).ToList();
        lastEnter.Clear();
        foreach (var item in sortedList)
        {
            lastEnter.Add(item);
        }
    }


    private void Button_Desc(object? sender, RoutedEventArgs e)
    {
        var sortedList = dataLastEnter.OrderByDescending(it => it.EnterDatetime).ToList();
        lastEnter.Clear();
        foreach (var descList in sortedList)
        {
            lastEnter.Add(descList);
        }
    }
}