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

namespace NexusShell.Views;

public partial class NexusCalculatorView
{
    public NexusCalculatorView()
    {
        InitializeComponent();
        Loaded += (_, _) => Focus();
    }

    private void CalculatorView_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (DataContext is not NexusCalculatorViewModel viewModel)
        {
            return;
        }

        var buttonId = MapKey(e.Key);
        if (buttonId is null)
        {
            return;
        }

        viewModel.Press(buttonId);
        e.Handled = true;
    }

    private static string? MapKey(Key key) => key switch
    {
        Key.D0 or Key.NumPad0 => "0",
        Key.D1 or Key.NumPad1 => "1",
        Key.D2 or Key.NumPad2 => "2",
        Key.D3 or Key.NumPad3 => "3",
        Key.D4 or Key.NumPad4 => "4",
        Key.D5 or Key.NumPad5 => "5",
        Key.D6 or Key.NumPad6 => "6",
        Key.D7 or Key.NumPad7 => "7",
        Key.D8 or Key.NumPad8 => "8",
        Key.D9 or Key.NumPad9 => "9",
        Key.Add or Key.OemPlus => "+",
        Key.Subtract or Key.OemMinus => "-",
        Key.Multiply => "*",
        Key.Divide => "/",
        Key.Oem2 when Keyboard.Modifiers == ModifierKeys.None => "/",
        Key.Decimal or Key.OemPeriod or Key.OemComma => ".",
        Key.Enter or Key.Return => "=",
        Key.Escape => "C",
        Key.Back => "Backspace",
        _ => null,
    };
}
