package eu.dnetlib.data.collector.plugins.datasources;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import eu.dnetlib.data.collector.plugins.HttpConnector;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.*;

@Ignore
public class Re3DataRepositoriesIteratorTest {

	private static final Log log = LogFactory.getLog(Re3DataRepositoriesIteratorTest.class);

	private static final String TMP_DIR = "/tmp/re3data/";
	int countRepos = 0;
	int expectedRepos = 2189;
	private Re3DataRepositoriesIterator re3dataIterator;
	private String baseURL = "https://www.re3data.org";
	private String repoListURL = baseURL + "/api/v1/repositories";

	private HttpConnector httpConnector;

	@Before
	public void setUp() throws Exception {
		httpConnector = new HttpConnector();
		String input = httpConnector.getInputSource(repoListURL);
		re3dataIterator = new Re3DataRepositoriesIterator(IOUtils.toInputStream(input, "UTF-8"), baseURL, httpConnector);

		File tmpDir = new File(TMP_DIR);
		if (tmpDir.exists()) {
			log.info("deleting directory: " + tmpDir.getAbsolutePath());
			FileUtils.forceDelete(tmpDir);
		}
		log.info("creating directory: " + tmpDir.getAbsolutePath());
		FileUtils.forceMkdir(tmpDir);
	}

	@Test
	public void testHasNext() {
		assertTrue(re3dataIterator.hasNext());
	}

	@Test
	public void testNext() {
		String repo = null;
		if (re3dataIterator.hasNext()) {
			repo = re3dataIterator.next();
		}
		assertNotNull(repo);
	}

	@Test(expected = UnsupportedOperationException.class)
	public void testRemove() {
		re3dataIterator.remove();
	}

	@Test
	public void testIterator() throws IOException {

		for (String repo : re3dataIterator) {

				countRepos++;
				assertNotNull(repo);
				FileOutputStream st = new FileOutputStream(TMP_DIR + countRepos + ".xml");
				IOUtils.write(repo, st);
				IOUtils.closeQuietly(st);


		}
		assertEquals(expectedRepos, countRepos);
	}

	@Test
	public void testBadIterator() throws IOException {

		final Iterator<String> iter = re3dataIterator.iterator();

		while (iter.hasNext()) {

			iter.hasNext();
			iter.next();

			countRepos++;
		}
		assertEquals(expectedRepos, countRepos);
	}


}
