using System;
using System.IO;
using StellaOps.Plugin.Hosting;
using StellaOps.Scanner.WebService.Options;

namespace StellaOps.Scanner.WebService.Hosting;

internal static class ScannerPluginHostFactory
{
    public static PluginHostOptions Build(ScannerWebServiceOptions options, string contentRootPath)
    {
        ArgumentNullException.ThrowIfNull(options);
        ArgumentNullException.ThrowIfNull(contentRootPath);

        var baseDirectory = options.Plugins.BaseDirectory;
        if (string.IsNullOrWhiteSpace(baseDirectory))
        {
            baseDirectory = Path.Combine(contentRootPath, "..");
        }
        else if (!Path.IsPathRooted(baseDirectory))
        {
            baseDirectory = Path.GetFullPath(Path.Combine(contentRootPath, baseDirectory));
        }

        var pluginsDirectory = options.Plugins.Directory;
        if (string.IsNullOrWhiteSpace(pluginsDirectory))
        {
            pluginsDirectory = Path.Combine("plugins", "scanner");
        }

        if (!Path.IsPathRooted(pluginsDirectory))
        {
            pluginsDirectory = Path.Combine(baseDirectory, pluginsDirectory);
        }

        var hostOptions = new PluginHostOptions
        {
            BaseDirectory = baseDirectory,
            PluginsDirectory = pluginsDirectory,
            PrimaryPrefix = "StellaOps.Scanner"
        };

        foreach (var additionalPrefix in options.Plugins.OrderedPlugins)
        {
            hostOptions.PluginOrder.Add(additionalPrefix);
        }

        foreach (var pattern in options.Plugins.SearchPatterns)
        {
            hostOptions.SearchPatterns.Add(pattern);
        }

        return hostOptions;
    }
}
