package eu.dnetlib.data.transform;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Created by claudio on 12/12/2016.
 */
public class OntologyLoaderTest {

	private String basePath = "/eu/dnetlib/bootstrap/profiles/OntologyDSResources/OntologyDSResourceType/";

	@Test
	public void testLoadOntologyFromCp() {

		final InputStream i = getClass().getResourceAsStream(basePath + "publication_publication_relations.xml");

        Ontology o = OntologyLoader.loadOntologyFromCp(i);
        checkOntology(o);

        String providedBy = o.inverseOf("isSupplementedBy");
        assertEquals(providedBy, "isSupplementTo");

        String provides = o.inverseOf("isPartOf");
        assertEquals(provides, "hasPart");
    }

	@Test
	public void testLoadOntologiesFromCp() throws IOException {

		OntologyLoader.loadOntologiesFromCp().values().forEach(o -> checkOntology(o));
	}

	@Test
	public void testLoadOntologiesSerialization() throws IOException {

		final Ontologies o = OntologyLoader.loadOntologiesFromCp();
		assertNotNull(o);
		final String json = o.toJson(true);

		System.out.println(json);

		assertTrue(StringUtils.isNoneBlank(json));

		final Ontologies o1 = OntologyLoader.loadOntologies(json);

		assertNotNull(o1);

		o1.entrySet().forEach(e -> checkOntology(e.getValue()));
	}

	private void checkOntology(Ontology o) {
		Assert.assertNotNull(o);
		Assert.assertTrue(StringUtils.isNotBlank(o.getCode()));
		Assert.assertTrue(StringUtils.isNotBlank(o.getDescription()));
		Assert.assertNotNull(o.getTerms().values());

		o.getTerms().values().forEach(it -> {
			Assert.assertTrue(StringUtils.isNotBlank(it.getCode()));
			Assert.assertTrue(StringUtils.isNotBlank(it.getEncoding()));
			Assert.assertTrue(StringUtils.isNotBlank(it.getEnglishName()));
			Assert.assertTrue(StringUtils.isNotBlank(it.getNativeName()));
			Assert.assertTrue(StringUtils.isNotBlank(it.getInverseCode()));
			Assert.assertNotNull(o.getTerms().get(it.getInverseCode()));
		});
	}
}
