package cd.casic.plugin.utils;

import cd.casic.plugin.dataobject.dto.PluginSpecStorage;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

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

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/12 19:33
 * @version: 1.0
 */
@Component
public class YamlUnstructuredLoader extends YamlProcessor {
    private static final DocumentMatcher DEFAULT_UNSTRUCTURED_MATCHER = properties -> {
        if (properties.containsKey("id")
                && properties.containsKey("version")
                && (properties.containsKey("class")
                || properties.containsKey("metadata"))) {
            return YamlProcessor.MatchStatus.FOUND;
        }
        return MatchStatus.NOT_FOUND;
    };

    public YamlUnstructuredLoader(Resource... resources) {
        setResources(resources);
        setDocumentMatchers(DEFAULT_UNSTRUCTURED_MATCHER);
    }

    public PluginSpecStorage load() {
        List<PluginSpecStorage> pluginDescriptor = new ArrayList<>();
        this.process(((properties, map) -> {
            pluginDescriptor.add(PluginDescriptorUtils.propertiesToStorage(properties));
        }));
        return pluginDescriptor.get(0);
    }
}
