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

namespace demko_term;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        PasswordTextBox.PasswordChar = '•';
    }

    private void AuthButton_OnClick(object? sender, RoutedEventArgs e)
    {
        using var context = new DemoCourseworkContext();

        var loginText = LoginTextBox?.Text?.Trim();
        var password = PasswordTextBox?.Text;

        if (string.IsNullOrEmpty(loginText) || string.IsNullOrEmpty(password))
        {
            return;
        }
        
        var employee = context.Employees
            .Include(e => e.Position)
            .FirstOrDefault(e => e.Login == loginText);

        if (employee != null && password == employee.Password)
        {
            var history = new EmployeesHistory
            {
                EmployeeId = employee.Id,
                LastLogin = DateTime.Now,
                SuccessLogin = true
            };
            context.EmployeesHistories.Add(history);
            context.SaveChanges();
            
            switch (employee.PositionId)
            {
                case 1:
                    new VolunteerWindow(employee).ShowDialog(this);
                    break;
                case 2:
                    new ManagerWindow(employee).ShowDialog(this);
                    break;
                case 3:
                    new WorkerWindow(employee).ShowDialog(this);
                    break;
                default:
                    new BlankWindow().ShowDialog(this);
                    return;
            }
        }
        else
        {
            var history = new EmployeesHistory
            {
                EmployeeId = employee.Id,
                LastLogin = DateTime.Now,
                SuccessLogin = false
            };
            context.EmployeesHistories.Add(history);
            context.SaveChanges();
        }
    }

    private void ShowPasswordCheckBox_OnCheck(object sender, RoutedEventArgs e)
    {
        PasswordTextBox.PasswordChar = '\0';
    }

    private void ShowPasswordCheckBox_OnUncheck(object sender, RoutedEventArgs e)
    {
        PasswordTextBox.PasswordChar = '•';
    }
}
