package org.wyrez.shootingstars.data;

/*
 * Copyright (C) 2013 Darth Affe <http://wyrez.org> and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.concurrent.CountDownLatch;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;

/**
 *
 * @author Darth Affe
 */
public class OggConverter {

    private CountDownLatch completionLatch;
    private final MediaPlayerFactory mediaPlayerFactory;
    private final MediaPlayer mediaPlayer;
    private boolean success = false;

    public OggConverter() {
        mediaPlayerFactory = new MediaPlayerFactory();
        mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
        mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
            @Override
            public void finished(MediaPlayer mediaPlayer) {
                System.out.println("Rip completed successfully");
                success = true;
                completionLatch.countDown();
            }

            @Override
            public void error(MediaPlayer mediaPlayer) {
                System.out.println("Rip failed");
                success = false;
                completionLatch.countDown();
            }
        });
    }

    public void convert(String in, String out, int bitrate) throws Exception {
        System.out.println("Convert '" + in + "' to '" + out + "'...");
        completionLatch = new CountDownLatch(1);
        mediaPlayer.playMedia(in, String.format(
                "sout=#transcode{acodec=vorb,channels=2,ab=%d,samplerate=44100,vcodec=dummy}:standard{dst=%s,mux=ogg,access=file}",
                bitrate, out));

        try {
            completionLatch.await();
            if (!success) {
                throw new Exception("failed conversion...");
            }
        } catch (InterruptedException e) {
            System.out.println("failed...");
            throw new Exception("failed conversion...");
        }
    }

    public void cleanup() {
        mediaPlayer.release();
        mediaPlayerFactory.release();
    }
}
