using System.Linq;
using Avalonia.Controls;
using Avalonia.Interactivity;
using FirstSlice.Models;
using Microsoft.EntityFrameworkCore;

namespace FirstSlice;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        RoleTable.Items = Helper.GetContext().Roles.ToList();
        UserTable.Items = Helper.GetContext().Users.Include(x => x.FkRole).ToList();
    }

    private async void OnAddUserClick(object? sender, RoutedEventArgs e)
    {
        var userWindow = new UserWindow();
        await userWindow.ShowDialog(this);
        
        UserTable.Items = Helper.GetContext().Users.Include(x => x.FkRole).ToList();
    }

    private void OnDeleteUserClick(object? sender, RoutedEventArgs e)
    {
        var user = UserTable.SelectedItem as User;

        Helper.GetContext().Users.Remove(user);
        Helper.GetContext().SaveChanges();
        
        UserTable.Items = Helper.GetContext().Users.Include(x => x.FkRole).ToList();
    }
    
    private async void OnUserTableDoubleTapped(object? sender, RoutedEventArgs e)
    {
        DataGrid grid = sender as DataGrid;
        var user = grid.SelectedItem as User;
        
        var userWindow = new UserWindow(user);
        await userWindow.ShowDialog(this);
        
        UserTable.Items = Helper.GetContext().Users.Include(x => x.FkRole).ToList();
    }

    private async void OnAddRoleClick(object? sender, RoutedEventArgs e)
    {
        var role = new RoleWindow();
        await role.ShowDialog(this);
        
        RoleTable.Items = Helper.GetContext().Roles.ToList();
    }

    private void OnDeleteRoleClick(object? sender, RoutedEventArgs e)
    {
        var role = RoleTable.SelectedItem as Role;

        Helper.GetContext().Roles.Remove(role);
        Helper.GetContext().SaveChanges();
        
        RoleTable.Items = Helper.GetContext().Roles.ToList();
    }

    private async void OnRoleTableDoubleTapped(object? sender, RoutedEventArgs e)
    {
        DataGrid grid = sender as DataGrid;
        var role = grid.SelectedItem as Role;
        
        var roleWindow = new RoleWindow(role);
        await roleWindow.ShowDialog(this);
        
        RoleTable.Items = Helper.GetContext().Roles.ToList();
    }
}