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

namespace NexusShell.Controls.Dialogs;

public partial class NexusSaveFileDialogWindow : Controls.NexusWindow
{
    public string DialogTitle { get; set; } = "Gem fil";
    public string Filter { get; set; } = "Alle filer|*.*";
    public string? InitialDirectory { get; set; }
    public string? DefaultExt { get; set; }
    public string? SuggestedFileName { get; set; }
    public string? SelectedFileName { get; private set; }

    public NexusSaveFileDialogWindow()
    {
        InitializeComponent();
        Loaded += (_, _) =>
        {
            TitleText.Text = DialogTitle;
            if (!string.IsNullOrWhiteSpace(SuggestedFileName))
            {
                PathBox.Text = SuggestedFileName;
            }
        };
    }

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

        if (!string.IsNullOrWhiteSpace(DefaultExt))
        {
            dialog.DefaultExt = DefaultExt;
        }

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

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

        SelectedFileName = dialog.FileName;
        PathBox.Text = dialog.FileName;
    }

    private void Save_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();
    }
}
