package zall.transcoder;

import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.video.ConverterFactory;
import com.xuggle.xuggler.video.IConverter;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 *
 */
class FrameGrabListener extends MediaToolAdapter {
	private long totalLength;
	private long grabAt;
	private File outputFile;

	public FrameGrabListener(IMediaReader reader, File outputFile, double at) {
		if( !reader.isOpen() )
            reader.open(); // read container
		this.totalLength = reader.getContainer().getDuration();
		this.outputFile = outputFile;
        setAtProgress(at);
	}

	@Override
	public void onVideoPicture(IVideoPictureEvent event) {
		try{
			long currentLength = event.getTimeStamp();

			if( grabAt > 0 && currentLength > grabAt ){
				System.out.println("\nScreanshoot!!!");

				ConverterFactory.Type mConverterType = ConverterFactory.findRegisteredConverter(
						ConverterFactory.XUGGLER_BGR_24);
				IConverter mVideoConverter = ConverterFactory.createConverter(
						mConverterType.getDescriptor(),
						event.getPicture());

				ImageIO.write(
							mVideoConverter.toImage(event.getPicture()),
							"png",
							outputFile);
				grabAt = -1;
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public void setAtProgress(double procent){
		grabAt = (long)(totalLength * procent);
	}
}
