package extraction;

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

import org.apache.log4j.Logger;

import bean.Track;
import utils.AudioUtils;

public class TrackExtractor {
	
	private static final Logger logger = Logger.getLogger(TrackExtractor.class);
	
	private final SingleTrackExtractor singleTrackExtractor;
	
	private final DateTimeFormatter formatter;
	
	private final AudioUtils audioUtils;
	
	public TrackExtractor(SingleTrackExtractor singleTrackExtractor) {
		
		this.singleTrackExtractor = singleTrackExtractor;
		this.audioUtils = new AudioUtils();
		this.formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");;
	}

	public List<Track> extract(File audioFile, int trackLengthSecs, LocalDateTime initialDateTime) {

		int idGenerator = 0;
		
		LocalDateTime localDateTime = initialDateTime;
		
		List<Track> extractedTracks = new ArrayList<>();
		
		LocalTime initialTime = LocalTime.of(0, 0, 0);
		LocalTime duration = LocalTime.MIN.plusSeconds(trackLengthSecs);
		
		String trackName = this.formatter.format(localDateTime) + ".mp3";
		
		File extractedTrack = null;
		
		int totalTracks = (int)this.audioUtils.getMp3DurationInSeconds(audioFile) / trackLengthSecs;
		
		for (int i = 0 ; i < totalTracks ; i++) {
		
			logger.info("extract: Going to extract "+trackName);
			
			extractedTrack = this.singleTrackExtractor.extract(audioFile, initialTime, duration, trackName);			
			
			extractedTracks.add(new Track(idGenerator, extractedTrack, localDateTime));
			
			localDateTime = localDateTime.plusSeconds(trackLengthSecs);
			
			initialTime = initialTime.plusSeconds(trackLengthSecs);
			
			trackName = this.formatter.format(localDateTime) + ".mp3";		
		}
		
		logger.info("extract: Extracted "+extractedTracks.size()+" tracks from '"+audioFile.getAbsolutePath()+"' with length "+trackLengthSecs+" seconds, starting at "+initialDateTime);
		
		return extractedTracks;
	}
}
