package leigh.audio.bpm;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.smpte.Timecode;
import v4lk.lwbd.util.Beat;

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

/**
 * Wrapper for the V4LK beat detector implementation. This implementation is intended to be used with 44.1khz
 * mono MP3 files.
 *
 * @author Alex Leigh
 */
public class V4LKBeatDetector {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(V4LKBeatDetector.class);

    public static List<Timecode> detect(File audioFile) throws IOException {
        logger.info("Processing audio...");

        Beat[] beats = v4lk.lwbd.BeatDetector.detectBeats(audioFile, v4lk.lwbd.BeatDetector.AudioType.MP3);
        ArrayList<Timecode> output = new ArrayList<>();

        logger.info("Processing finished.");

        Timecode last = null;

        for (Beat b : beats) {
            if (b.energy > .25) {
                Timecode tc = new Timecode((float) b.timeMs / 1000, Timecode.Type.TYPE_VIDEO_FILM);
                // Dampen to no more than 120BPM
                if (last != null) {
                    double lastFrame = last.toFrames();
                    if (tc.toFrames() - lastFrame < 6) continue;
                }
                last = tc;
                output.add(tc);
                logger.info("Detected beat: {} [tc: {}]", b, tc);
            }
        }
        return output;
    }
}
