using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HC_APTBS.Services;
namespace HC_APTBS.ViewModels.Dialogs
{
///
/// ViewModel for the user authentication dialog shown before report generation.
/// Validates operator credentials against the stored user list.
///
public sealed partial class UserCheckViewModel : ObservableObject
{
private readonly IConfigurationService _config;
private readonly ILocalizationService _loc;
/// Initialises the dialog, optionally pre-filling the last used username.
public UserCheckViewModel(IConfigurationService config, ILocalizationService loc, string lastUsername = "")
{
_config = config;
_loc = loc;
_username = lastUsername;
}
// ── Bindable properties ───────────────────────────────────────────────────
/// Username entered by the operator.
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AcceptCommand))]
private string _username = string.Empty;
/// Password entered by the operator (set from code-behind PasswordChanged handler).
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AcceptCommand))]
private string _password = string.Empty;
// ── Dialog result ─────────────────────────────────────────────────────────
/// True if the user authenticated successfully.
public bool Accepted { get; private set; }
/// The validated username, available after is true.
public string AuthenticatedUser { get; private set; } = string.Empty;
// ── Commands ──────────────────────────────────────────────────────────────
/// Validates credentials and closes the dialog on success.
[RelayCommand(CanExecute = nameof(CanAccept))]
private void Accept()
{
if (_config.ValidateUser(Username, Password))
{
AuthenticatedUser = Username;
Accepted = true;
RequestClose?.Invoke();
}
else
{
MessageBox.Show(
_loc.GetString("Error.AuthInvalid"),
_loc.GetString("Error.AuthTitle"),
MessageBoxButton.OK,
MessageBoxImage.Stop);
}
}
private bool CanAccept() => !string.IsNullOrWhiteSpace(Username)
&& !string.IsNullOrEmpty(Password);
/// Cancels authentication and closes the dialog.
[RelayCommand]
private void Cancel()
{
Accepted = false;
RequestClose?.Invoke();
}
// ── Events ────────────────────────────────────────────────────────────────
/// Raised when the dialog should close itself.
public event System.Action? RequestClose;
}
}