package cd.casic.plugin.pf4j;

import cd.casic.plugin.PluginProperties;
import cn.hutool.core.collection.CollectionUtil;
import org.pf4j.PluginStatusProvider;

import java.util.HashSet;
import java.util.Set;

public class OpsPluginStatusProvider implements PluginStatusProvider {

    private final Set<String> enabledPlugins = new HashSet<>();
    private final Set<String> disabledPlugins = new HashSet<>();

    public OpsPluginStatusProvider(PluginProperties pluginProperties) {
        this.enabledPlugins.addAll(pluginProperties.getEnabledPlugins());
        this.disabledPlugins.addAll(pluginProperties.getDisabledPlugins());
    }

    public static boolean isPropertySet(PluginProperties pluginProperties) {
        return CollectionUtil.isNotEmpty(pluginProperties.getEnabledPlugins())
                || CollectionUtil.isNotEmpty(pluginProperties.getDisabledPlugins());
    }

    @Override
    public boolean isPluginDisabled(String pluginId) {
        if (disabledPlugins.contains(pluginId)) {
            return true;
        }
        return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId);
    }

    @Override
    public void disablePlugin(String pluginId) {
        if (isPluginDisabled(pluginId)) {
            return;
        }
        disabledPlugins.add(pluginId);
        enabledPlugins.remove(pluginId);
    }

    @Override
    public void enablePlugin(String pluginId) {
        if (!isPluginDisabled(pluginId)) {
            return;
        }
        enabledPlugins.add(pluginId);
        disabledPlugins.remove(pluginId);
    }
}
