using Windows.System;
using YMhut.Box.Core.App;
using YMhut.Box.Core.Logging;

namespace YMhut.Box.WinUI.Services;

public enum ToolLinkTarget
{
    SafeBrowser,
    SystemBrowser
}

public interface IToolLinkNavigationService
{
    Task<bool> OpenAsync(string? value, ToolLinkTarget target = ToolLinkTarget.SafeBrowser, string? title = null, CancellationToken cancellationToken = default);
}

public sealed class ToolLinkNavigationService(
    AppPaths paths,
    IIndependentWindowHostLauncher windowHostLauncher,
    ILogService? logService = null) : IToolLinkNavigationService
{
    public async Task<bool> OpenAsync(
        string? value,
        ToolLinkTarget target = ToolLinkTarget.SafeBrowser,
        string? title = null,
        CancellationToken cancellationToken = default)
    {
        if (!TryHttpUri(value, out var uri))
        {
            return false;
        }

        cancellationToken.ThrowIfCancellationRequested();
        if (target == ToolLinkTarget.SystemBrowser)
        {
            await Launcher.LaunchUriAsync(uri).AsTask().ConfigureAwait(true);
            return true;
        }

        await windowHostLauncher.LaunchAsync(
            IndependentWindowHostOptions.Browser(
                string.IsNullOrWhiteSpace(title) ? AppLocalizer.T("安全浏览器", "Safe Browser") : title,
                uri.AbsoluteUri,
                paths),
            cancellationToken).ConfigureAwait(true);
        _ = logService?.WriteAsync(
            "Information",
            "navigation",
            "Opened link in safe browser",
            uri.GetLeftPart(UriPartial.Authority),
            cancellationToken);
        return true;
    }

    private static bool TryHttpUri(string? value, out Uri uri)
    {
        uri = null!;
        return Uri.TryCreate(value, UriKind.Absolute, out var candidate) &&
            candidate.Scheme is "http" or "https" &&
            (uri = candidate) is not null;
    }
}
