package org.xbib.datastructures.yaml.tiny.test;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.xbib.datastructures.api.Node;
import org.xbib.datastructures.api.Parser;
import org.xbib.datastructures.yaml.tiny.Yaml;
import org.xbib.datastructures.yaml.tiny.YamlParser;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class YamlParserTest {

    @Test
    public void parseList() throws Exception {
        // exact spacing (we have no space management yet)
        String s = "test: \n  - a\n  - b\n";
        Reader reader = new StringReader(s);
        Parser parser = new YamlParser();
        Node<?> node = parser.parse(reader);
        Yaml yaml = new Yaml(node);
        StringWriter writer = new StringWriter();
        yaml.createGenerator(node).generate(writer);
        String s1 = writer.toString();
        assertEquals(s, s1);
    }

    @Test
    public void example() throws Exception {
        InputStream inputStream = getClass().getResourceAsStream("example.yml");
        if (inputStream != null) {
            roundTrip(inputStream);
        }
    }

    @Disabled("yaml space management")
    @Test
    public void test() throws Exception {
        InputStream inputStream = getClass().getResourceAsStream("test.yml");
        if (inputStream != null) {
            roundTrip(inputStream);
        }
    }

    @Test
    public void hippie() throws Exception {
        InputStream inputStream = getClass().getResourceAsStream("hippie.yml");
        if (inputStream != null) {
           roundTrip(inputStream);
        }
    }

    @Test
    public void sshKey() throws Exception {
        InputStream inputStream = getClass().getResourceAsStream("key.yaml");
        if (inputStream != null) {
            roundTrip(inputStream);
        }
    }

    private static void roundTrip(InputStream inputStream) throws Exception {
        Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        Parser parser = new YamlParser();
        Node<?> node = parser.parse(reader);
        Yaml yaml = new Yaml(node);
        StringWriter writer = new StringWriter();
        yaml.createGenerator(node).generate(writer);
        String s1 = writer.toString();
        Node<?> node2 = parser.parse(new StringReader(writer.toString()));
        writer = new StringWriter();
        yaml.createGenerator(node2).generate(writer);
        String s2 = writer.toString();
        assertEquals(s1, s2);
    }
}
