using System.IO;
using NexusShell.Controls.Dialogs;
using NexusShell.Models;

namespace NexusShell.Services;

public interface INexusFileOpenRouter
{
    void OpenWithApp(NexusDefaultAppId appId, string filePath);
}

public sealed class NexusFileOpenService
{
    private readonly NexusDefaultAppsService _defaultApps;
    private INexusFileOpenRouter? _router;

    public NexusFileOpenService(NexusDefaultAppsService defaultApps)
    {
        _defaultApps = defaultApps;
    }

    public void SetRouter(INexusFileOpenRouter router) => _router = router;

    public bool TryOpenFile(string filePath, System.Windows.Window? owner, out string? error)
    {
        error = null;
        if (!File.Exists(filePath))
        {
            error = "Filen findes ikke.";
            return false;
        }

        var handler = _defaultApps.ResolveHandler(filePath);
        if (_router is not null)
        {
            _router.OpenWithApp(handler, filePath);
            return true;
        }

        error = "Nexus app-router er ikke tilgængelig.";
        return false;
    }

    public bool TryOpenWithDialog(string filePath, System.Windows.Window? owner, out string? error)
    {
        error = null;
        if (!File.Exists(filePath))
        {
            error = "Filen findes ikke.";
            return false;
        }

        var dialog = new NexusOpenWithDialog
        {
            FilePath = filePath,
            Title = $"Åbn med — {Path.GetFileName(filePath)}",
        };

        if (dialog.ShowDialog(owner) != true || dialog.SelectedApp is not { } selected)
        {
            return false;
        }

        if (_router is null)
        {
            error = "Nexus app-router er ikke tilgængelig.";
            return false;
        }

        _router.OpenWithApp(selected, filePath);
        return true;
    }
}
