package eu.dnetlib.dlms.benchmark;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openrdf.model.Statement;
import org.openrdf.model.Value;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Test class for RecursiveLoader.
 * 
 * @author lexis
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class RecursiveLoaderTest {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(RecursiveLoaderTest.class);

	/** Entity under test. */
	@Resource
	private RecursiveLoader recursiveLaoder;
	/** Directory to walk. */
	@Resource
	private String startDirPath;

	/** triplestore repository. */
	@Resource
	private Repository repository;

	/**
	 * Clears the triplestore.
	 * 
	 * @throws RepositoryException
	 *             accessing the repository
	 */
	@Before
	public void clearTriplestore() throws RepositoryException {
		RepositoryConnection con = this.repository.getConnection();
		con.clear();
		con.close();
	}

	/**
	 * Test method for {@link eu.dnetlib.dlms.benchmark.RecursiveLoader#startWalking(java.lang.String)}.
	 * 
	 * @throws IOException
	 *             walking the directory
	 * @throws RepositoryException
	 *             accessing the triplestore
	 */
	@Test
	public void testStartWalking() {
		try {
			this.recursiveLaoder.startWalking(this.startDirPath);
			log.info("Total files processed = " + this.recursiveLaoder.getTotalFiles());
		} catch (Exception e) {
			log.error("Exception occurred after processing " + this.recursiveLaoder.getTotalFiles() + ". Exception: " + e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * Asks the triplestore for all triples and logs them. The given connection must be close by the caller.
	 * 
	 * @param con
	 *            open RepositoryConnection to the triplestore
	 * @throws RepositoryException
	 *             connecting to the repository
	 */
	@SuppressWarnings("unused")
	private void logAllTriples(final RepositoryConnection con) throws RepositoryException {
		log.debug("Now printing all triples in triplestore");
		RepositoryResult<Statement> res = con.getStatements(null, null, (Value) null, false);
		int total = 0;
		while (res.hasNext()) {
			log.debug(res.next());
			total++;
		}
		res.close();
		log.info("Total number of triples = " + total);
	}

}
