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

namespace FirstSlice;

public partial class UserWindow : Window
{
    private User user_ = null;    
    
    public UserWindow()
    {
        InitializeComponent();

        ComboRole.Items = Helper.GetContext().Roles.ToList();
    }
    
    public UserWindow(User user)
    {
        InitializeComponent();

        user_ = user;
        TextFullName.Text = user_.Fullname;
        TextBirthday.Text = user_.Birthday;
        TextAddress.Text = user_.Address;
        TextPhoneNumber.Text = user_.Phonenumber;
        ComboRole.Items = Helper.GetContext().Roles.ToList();
        ComboRole.SelectedItem = user_.FkRole;
    }

    private void OnSaveUserClick(object? sender, RoutedEventArgs e)
    {
        if (String.IsNullOrWhiteSpace(TextFullName.Text)    || 
            String.IsNullOrWhiteSpace(TextAddress.Text)     || 
            String.IsNullOrWhiteSpace(TextBirthday.Text)    || 
            String.IsNullOrWhiteSpace(TextPhoneNumber.Text) || 
            ComboRole.SelectedItem == null)
        {
            return;
        }
        
        if (user_ != null)
        {
            var role = ComboRole.SelectedItem as Role;
            user_.Fullname = TextFullName.Text;
            user_.Address = TextAddress.Text;
            user_.Birthday = TextBirthday.Text;
            user_.Phonenumber = TextPhoneNumber.Text;
            user_.FkRole = role;
            user_.FkRoleId = role.Id;

            Helper.GetContext().Update(user_);
            Helper.GetContext().SaveChanges();
            this.Close();
        }
        else
        {
            var newUser = new User();
            var role = ComboRole.SelectedItem as Role;
            newUser.Fullname = TextFullName.Text;
            newUser.Address = TextAddress.Text;
            newUser.Birthday = TextBirthday.Text;
            newUser.Phonenumber = TextPhoneNumber.Text;
            newUser.FkRole = role;
            newUser.FkRoleId = role.Id;
            
            Helper.GetContext().Add(newUser);
            Helper.GetContext().SaveChanges();
            this.Close();
        }
        
    }
}