using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using NexusShell.ViewModels;

namespace NexusShell.Views;

public partial class LoginView : UserControl
{
    public LoginView()
    {
        InitializeComponent();
    }

    private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
    {
        if (DataContext is LoginViewModel vm)
        {
            vm.Password = PasswordBox.Password;
        }
    }

    private void LoginView_OnLoaded(object sender, RoutedEventArgs e)
    {
        Dispatcher.BeginInvoke(() =>
        {
            PasswordBox.Focus();
            Keyboard.Focus(PasswordBox);
        });
    }

    private void LoginView_OnKeyDown(object sender, KeyEventArgs e)
    {
        TrySubmitOnEnter(e);
    }

    private void PasswordBox_OnKeyDown(object sender, KeyEventArgs e)
    {
        TrySubmitOnEnter(e);
    }

    private void TrySubmitOnEnter(KeyEventArgs e)
    {
        if (e.Key != Key.Enter || DataContext is not LoginViewModel vm)
        {
            return;
        }

        if (string.IsNullOrWhiteSpace(PasswordBox.Password))
        {
            PasswordBox.Focus();
            e.Handled = true;
            return;
        }

        if (vm.LoginCommand.CanExecute(null))
        {
            vm.LoginCommand.Execute(null);
            e.Handled = true;
        }
    }

    public void ClearPassword() => PasswordBox.Password = string.Empty;
}
