package ctbrec.recorder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;
import com.iheartradio.m3u8.data.TrackData;
import com.iheartradio.m3u8.data.TrackInfo;

import ctbrec.MpegUtil;


public class FastPlaylistGenerator extends PlaylistGenerator {
    static final Logger LOG = LoggerFactory.getLogger(FastPlaylistGenerator.class);

    FastPlaylistGenerator() {
    }

    @Override
    public File generate(File directory, String fileSuffix) throws IOException, ParseException, PlaylistException {
        LOG.info("Starting playlist generation for {}", directory);
        File[] files = scanDirectoryForSegments(directory, fileSuffix);

        // create a track containing all files
        List<TrackData> track = new ArrayList<>();
        int total = files.length;
        int done = 0;
        float duration = getFileDuration(files);
        for (File file : files) {
            track.add(new TrackData.Builder()
                    .withUri(file.getName())
                    .withTrackInfo(new TrackInfo(duration, file.getName()))
                    .build());
            done++;
            double percentage = (double) done / (double) total;
            updateProgressListeners(percentage);
        }

        return writePlaylistFile(directory, track);
    }

    private float getFileDuration(File[] files) {
        for (File file : files) {
            try {
                float duration = 0;
                if (file.getName().toLowerCase().endsWith(".ts")) {
                    duration = (float) MpegUtil.getFileDurationInSecs(file);
                    if (duration > 0) {
                        return duration;
                    }
                }
            } catch (Exception e) {
                LOG.warn("Couldn't determine duration for {}. Skipping this file.", file.getName());
            }
        }
        throw new RuntimeException("Couldn't determine playlist segment length");
    }

    @Override
    public void validate(File recDir) throws IOException, ParseException, PlaylistException {
        // don't validate anything
    }
}
