package io.papermc.paper.plugin.entrypoint.dependency;

import com.google.common.graph.MutableGraph;
import io.papermc.paper.plugin.configuration.PluginMeta;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("UnstableApiUsage")
public class DependencyUtil {

    @NotNull
    public static MutableGraph<String> buildDependencyGraph(@NotNull MutableGraph<String> dependencyGraph, @NotNull PluginMeta configuration) {
        List<String> dependencies = new ArrayList<>();
        dependencies.addAll(configuration.getPluginDependencies());
        dependencies.addAll(configuration.getPluginSoftDependencies());

        return buildDependencyGraph(dependencyGraph, configuration.getName(), dependencies, configuration.getLoadBeforePlugins());
    }

    @NotNull
    public static MutableGraph<String> buildDependencyGraph(@NotNull MutableGraph<String> dependencyGraph, String identifier, @NotNull Iterable<String> depends, @NotNull Iterable<String> loadBefore) {
        for (String dependency : depends) {
            dependencyGraph.putEdge(identifier, dependency);
        }

        for (String loadBeforeTarget : loadBefore) {
            dependencyGraph.putEdge(loadBeforeTarget, identifier);
        }

        dependencyGraph.addNode(identifier); // Make sure dependencies at least have a node
        return dependencyGraph;
    }

    // This adds a provided plugin to another plugin, basically making it seem like a "dependency"
    // in order to have plugins that need the provided plugin to load after the specified plugin name
    @NotNull
    public static MutableGraph<String> addProvidedPlugin(@NotNull MutableGraph<String> dependencyGraph, @NotNull String pluginName, @NotNull String providedName) {
        dependencyGraph.putEdge(pluginName, providedName);

        return dependencyGraph;
    }

}
