using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using demko_term.Models;

namespace demko_term;

public partial class CreateApplicantWindow : Window
{

    public int code_prew;
    
    public CreateApplicantWindow()
    {
        
        InitializeComponent();
        using var context = new DemoCourseworkContext();
        
        code_prew = context.Applicants.Select(a => a.Code).Max();
        CodeTextBox.Text = (code_prew + 1).ToString();
    }
    
    public void CreateApplicant_OnClick(object? sender, RoutedEventArgs e)
    {
        using var context = new DemoCourseworkContext();

        if (string.IsNullOrWhiteSpace(FirstNameTextBox.Text) ||
            string.IsNullOrWhiteSpace(LastNameTextBox.Text) ||
            string.IsNullOrWhiteSpace(PatronymicTextBox.Text) ||
            DatePicker.SelectedDate == null ||
            string.IsNullOrWhiteSpace(CodeTextBox.Text) ||
            string.IsNullOrWhiteSpace(PassportTextBox.Text) ||
            string.IsNullOrWhiteSpace(AddressTextBox.Text) ||
            string.IsNullOrWhiteSpace(EmailTextBox.Text) ||
            string.IsNullOrWhiteSpace(PhoneNumberTextBox.Text))
        {
            return;
        }
        
        var newApplicant = new Applicant
        {
            Firstname = FirstNameTextBox.Text,
            Lastname = LastNameTextBox.Text,
            Patronymic = PatronymicTextBox.Text,
            Date = DatePicker.SelectedDate?.DateTime,
            Code = int.Parse(CodeTextBox.Text),
            Passport = PassportTextBox.Text,
            Email = EmailTextBox.Text,
            Phone = PhoneNumberTextBox.Text,
            Address = AddressTextBox.Text
        };

        context.Applicants.Add(newApplicant);
        context.SaveChanges();

        Close();
    }
}