package cz.moneta.test.dsl.util.data;

import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import java.io.InputStream;

public class YamlLoader {
    private String filePath;
    private static Class<?> cls;
    public YamlLoader(String filePath, Class<?> cls) {
        this.filePath = filePath;
        this.cls = cls;
    }

    /**
     * This class representing an input stream of bytes.
     * Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.
     * @return the next byte of data, or -1 if the end of the stream is reached.
     */
    private InputStream createInputStream() {
        return this.getClass()
                .getClassLoader()
                .getResourceAsStream(filePath);
    }

    /**
     * Parse the YAML document in a stream and produce the corresponding Java object.
     * @return parsed object.
     */
    public <T> T parseObject() {
        Constructor constructor = new Constructor(cls);
        TypeDescription itemDescription = new TypeDescription(cls);
        itemDescription.addPropertyParameters("items", cls);
        constructor.addTypeDescription(itemDescription);
        Yaml yaml = new Yaml(constructor);
        return yaml.load(createInputStream());
    }
}

