using System.IO;
using System.Windows;
using Microsoft.Win32;

namespace NexusShell.Controls.Dialogs;

public partial class NexusOpenFileDialogWindow : Controls.NexusWindow
{
    public string DialogTitle { get; set; } = "Vælg fil";
    public string Filter { get; set; } = "Alle filer|*.*";
    public string? InitialDirectory { get; set; }
    public bool Multiselect { get; set; }
    public string? SelectedFileName { get; private set; }
    public string[]? SelectedFileNames { get; private set; }

    public NexusOpenFileDialogWindow()
    {
        InitializeComponent();
        Loaded += (_, _) => TitleText.Text = DialogTitle;
    }

    private void Browse_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new OpenFileDialog
        {
            Title = DialogTitle,
            Filter = Filter,
            Multiselect = Multiselect,
        };

        if (!string.IsNullOrWhiteSpace(InitialDirectory) && Directory.Exists(InitialDirectory))
        {
            dialog.InitialDirectory = InitialDirectory;
        }

        if (dialog.ShowDialog(this) != true)
        {
            return;
        }

        SelectedFileName = dialog.FileName;
        SelectedFileNames = dialog.FileNames;
        PathBox.Text = Multiselect ? string.Join("; ", dialog.FileNames) : dialog.FileName;
    }

    private void Open_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(SelectedFileName))
        {
            Browse_Click(sender, e);
            if (string.IsNullOrWhiteSpace(SelectedFileName))
            {
                return;
            }
        }

        DialogResult = true;
        Close();
    }

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