package cd.casic.plugin.core;

import cd.casic.plugin.config.PluginProperties;
import org.apache.commons.lang3.ArrayUtils;
import org.pf4j.PluginStatusProvider;

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

/**
 * @description: 读取配置文件，ops.plugin.enabled-plugins读取可用和非可用的
 * @author: mianbin
 * @date: 2025/5/13 10:44
 * @version: 1.0
 */
public class PropertyPluginStatusProvider implements PluginStatusProvider {

    private final List<String> enabledPlugins;
    private final List<String> disabledPlugins;

    public PropertyPluginStatusProvider(PluginProperties pluginProperties) {
        this.enabledPlugins = pluginProperties.getEnabledPlugins() != null
                ? Arrays.asList(pluginProperties.getEnabledPlugins()) : new ArrayList<>();
        this.disabledPlugins = pluginProperties.getDisabledPlugins() != null
                ? Arrays.asList(pluginProperties.getDisabledPlugins()) : new ArrayList<>();
    }

    public static boolean isPropertySet(PluginProperties pluginProperties) {
        return !ArrayUtils.isEmpty(pluginProperties.getEnabledPlugins())
                && !ArrayUtils.isEmpty(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);
    }
}
