package com.seer.teach.common.cache.support;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
import java.util.Properties;
import java.io.IOException;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public org.springframework.core.env.PropertySource<?> createPropertySource(@Nullable String name, EncodedResource encodedResource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());
        Properties properties = factory.getObject();
        if (properties == null) {
            throw new IllegalStateException("Failed to load YAML properties from " + encodedResource.getResource());
        }
        String sourceName = (name != null) ? name : encodedResource.getResource().getFilename();
        if (sourceName == null) {
            throw new IllegalStateException("Resource must have a filename");
        }
        return new PropertiesPropertySource(sourceName, properties);
    }
}