package eu.dnetlib.download.plugin;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class PathRetreiverTest {

    private static final Log log = LogFactory.getLog(PathRetreiverTest.class); // NOPMD by marko on 11/24/08 5:02 PM

    private TemporaryFolder t = new TemporaryFolder();

    private final PathRetreiver pt = new PathRetreiver();

    @Before
    public void setUp() throws IOException {
        t.create();

        IOUtils.readLines(getClass().getResourceAsStream("pmc_dirs.txt")).forEach(t::newFolder);
        for(final File dir : t.getRoot().listFiles(pathname -> pathname.isDirectory())) {
            int lower = Integer.parseInt(StringUtils.substringBefore(dir.getName(), "_").replaceAll("PMC", ""));
            int upper = Integer.parseInt(StringUtils.substringAfter(dir.getName(), "_").replaceAll("PMC", ""));

            for(int i=lower;i<lower+3 && i<upper;i++) {
               t.newFile(dir.getName() + "/" + i + ".xml");
            }
            for(int i=upper;i>upper-3 && i>lower;i--) {
                t.newFile(dir.getName() + "/" + i + ".xml");
            }
        }

        pt.setBase_path(t.getRoot().getPath());
    }


    @Test
    public void testPathRetriever() {

        String pathForPMCID = pt.getPathForPMCID(4676029);
        Assert.assertNotNull(pathForPMCID);
        log.info(pathForPMCID);

        pathForPMCID = pt.getPathForPMCID(4676028);
        Assert.assertNotNull(pathForPMCID);
        log.info(pathForPMCID);

        pathForPMCID = pt.getPathForPMCID(4676026);
        Assert.assertNull(pathForPMCID);
    }

    @After
    public void tearDown() {
        t.delete();
    }
}
