package extraction;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import bean.Track;
import constants.TestConstants;
import utils.AudioUtils;

public class TestTrackExtractor {
	
	private final AudioUtils audioUtils = new AudioUtils();
	private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
				
		PropertyConfigurator.configure("log4j.properties");
		FileUtils.deleteDirectory(TestConstants.tempDir);
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
		
		TestConstants.tempDir.mkdirs();
	}

	@After
	public void tearDown() throws Exception {
		
		FileUtils.deleteDirectory(TestConstants.tempDir);
	}

	@Test
	public void should_extract_all_tracks() throws Exception {
	
		SingleTrackExtractor singleExtractor = new SingleTrackExtractor(TestConstants.tempDir);
		
		int trackLength = this.findLargestDivisor(TestConstants.testAudioFileDurationSecs);
		
		TrackExtractor extractor = new TrackExtractor(singleExtractor);
		
		LocalDateTime initialTime = this.parseCreationTime(TestConstants.testAudioFile);
		
		List<Track> tracks = extractor.extract(TestConstants.testAudioFile, trackLength, initialTime);
		
		assertEquals(TestConstants.testAudioFileDurationSecs / trackLength, tracks.size());		
		
		for (Track track : tracks) {
			
			assertEquals(trackLength, audioUtils.getMp3DurationInSeconds(track.getTrack()), 1);
			
			assertEquals(initialTime, track.getCreationTime());
			
			initialTime = initialTime.plusSeconds(trackLength);
		}
	}
	
	private final LocalDateTime parseCreationTime(File audioFile) {
		
		return LocalDateTime.parse(audioFile.getName().replaceAll(".mp3", "").split("_")[1], formatter);
	}
	
	private final int findLargestDivisor(int length) {
		
		if (length % 2 == 0) {
			return length / 2;
		}
		
		int divisor = length / 2;
		
		while (--divisor > 1 && length % divisor != 0);
		
		return divisor;
	}
}
