using System.IO;
using System.Windows;
using System.Windows.Controls;
using NexusShell.Models;
using NexusShell.Services;

namespace NexusShell.Controls.Dialogs;

public partial class NexusOpenWithDialogWindow : Controls.NexusWindow
{
    public string DialogTitle { get; set; } = "Åbn med";
    public string? FilePath { get; set; }
    public NexusDefaultAppId? SelectedApp { get; private set; }

    public NexusOpenWithDialogWindow()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        TitleText.Text = DialogTitle;
        FileNameText.Text = string.IsNullOrWhiteSpace(FilePath)
            ? string.Empty
            : Path.GetFileName(FilePath);

        AppList.ItemsSource = NexusFileAssociations.GetOpenWithChoices();
        AppList.SelectedIndex = 0;
    }

    private void AppList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        OpenButton.IsEnabled = AppList.SelectedItem is NexusOpenWithChoice;
    }

    private void Open_Click(object sender, RoutedEventArgs e)
    {
        if (AppList.SelectedItem is not NexusOpenWithChoice choice)
        {
            return;
        }

        SelectedApp = choice.AppId;
        DialogResult = true;
        Close();
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }
}
