package org.xbib.settings.datastructures.yaml;

import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.xbib.datastructures.api.Node;
import org.xbib.datastructures.api.Parser;
import org.xbib.datastructures.tiny.TinyMap;
import org.xbib.settings.AbstractSettingsLoader;
import org.xbib.datastructures.api.DataStructure;
import org.xbib.datastructures.yaml.tiny.Yaml;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class YamlSettingsLoader extends AbstractSettingsLoader {

    public YamlSettingsLoader() {
    }

    @Override
    public DataStructure dataStructure() {
        return new Yaml();
    }

    @Override
    public Set<String> suffixes() {
        return Set.of("yml", "yaml");
    }

    @Override
    public Map<String, String> load(String source) throws IOException {
        // replace tabs with two whitespace (yaml does not accept tabs, but many users might use it still...)
        return super.load(source.replace("\t", "  "));
    }

    @Override
    protected Map<String, String> load(Parser parser, Reader reader) throws IOException {
        List<CharSequence> path = new ArrayList<>();
        TinyMap.Builder<String, String> map = TinyMap.builder();
        Node<?> node = parser.parse(reader);
        parseObject(node, map, path, null);
        return map.build();
    }
}
