package cd.casic.plugin.utils;

import lombok.extern.slf4j.Slf4j;
import org.pf4j.PluginManager;
import org.pf4j.PluginWrapper;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

@Slf4j
public abstract class FrontResourceUtils {
    private static final String FRONT_BUNDLE_LOCATION = "/static/ui";
    public static final String JS_BUNDLE = "/assets/main.js";
    public static final String CSS_BUNDLE = "/assets/style.css";

    @Nullable
    public static Resource getJsBundleResource(PluginManager pluginManager, String pluginName,
                                               String bundleName) {
        Assert.hasText(pluginName, "The pluginName must not be blank");
        Assert.hasText(bundleName, "Bundle name must not be blank");
        DefaultResourceLoader resourceLoader = getResourceLoader(pluginManager, pluginName);
        if (resourceLoader == null) {
            return null;
        }
        String path = FRONT_BUNDLE_LOCATION + bundleName;
        String simplifyPath = StringUtils.cleanPath(path);
        Resource resource = resourceLoader.getResource(simplifyPath);
        log.info("Get {} for plugin {} in the {} using {}", bundleName, pluginName, simplifyPath, resourceLoader);
        return resource.exists() ? resource : null;
    }

    @Nullable
    public static DefaultResourceLoader getResourceLoader(PluginManager pluginManager,
                                                          String pluginName) {
        Assert.notNull(pluginManager, "Plugin manager must not be null");
        PluginWrapper plugin = pluginManager.getPlugin(pluginName);
        if (plugin == null) {
            return null;
        }
        return new DefaultResourceLoader(plugin.getPluginClassLoader());
    }


}

