package cd.casic.plugin;

import cd.casic.plugin.utils.PluginDescriptorUtils;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.io.Resource;

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

import static cd.casic.plugin.utils.PluginDescriptorUtils.*;


public class PluginYamlProcessor extends YamlProcessor {
    /**
     * 检查这些必须有的属性是否存在
     */
    private static final DocumentMatcher DEFAULT_DOCUMENT_MATCHER = properties -> {
        if (properties.containsKey(PLUGIN_ID)
                && properties.containsKey(PLUGIN_VERSION)
                && properties.containsKey(PLUGIN_CLASS)){
            return MatchStatus.FOUND;
        }
        return MatchStatus.NOT_FOUND;
    };

    public PluginYamlProcessor(Resource... resources) {
        setResources(resources);
        setDocumentMatchers(DEFAULT_DOCUMENT_MATCHER);
    }

    /**
     * 读取yaml文件
     * @return PluginDescriptorStorage 插件的相关配置信息以及后续用于插件信息持久化存储的持久化对象
     */
    public PluginDescriptorStorage loadYaml() {
        List<PluginDescriptorStorage> pluginDescriptor = new ArrayList<>();
        this.process(((properties, map) -> {
            pluginDescriptor.add(PluginDescriptorUtils.propertiesToStorage(properties));
        }));

        return pluginDescriptor.get(0);
    }
}
