package eu.dnetlib.miscutils.collections;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import static org.junit.Assert.*; // NOPMD


public class TypeFilteredCollectionTest {

	private void checkContainsTestString(final Iterable<String> iter) {
		int count = 0; // NOPMD
		for (String el : iter) {
			assertEquals("check array", el, "test");
			count++; // NOPMD
		}
		assertEquals("check count", count, 1);
	}

	@Test
	public void testFilter() {
		final List<Object> list = new ArrayList<Object>();
		list.add(1);
		list.add("test");

		final TypeFilteredCollection<Object, String> tfc;
		tfc = new TypeFilteredCollection<Object, String>(list, String.class);
		checkContainsTestString(tfc);
	}

	@Test
	public void testNull() {
		final List<Object> list = new ArrayList<Object>();
		assertNotNull("dummy", list);
		
		list.add(null);
		list.add("test");

		final TypeFilteredCollection<Object, String> tfc;
		tfc = new TypeFilteredCollection<Object, String>(list, String.class);
		checkContainsTestString(tfc);
	}

	@Test
	public void testJDom() throws DocumentException {
		final String xmlSource = "<root><child/>xxxx<child/>xxxx</root>";

		final Document document = new SAXReader().read(new StringReader(xmlSource));

		@SuppressWarnings("unchecked")
		final List<Node> children = document.selectNodes("//child");

		final TypeFilteredCollection<Node, Element> tfc;
		tfc = new TypeFilteredCollection<Node, Element>(children, Element.class);
		for (Element el : tfc) {
			assertEquals("check array", el.asXML(), "<child/>");
		}

	}

}
