/*
 *  Keyframe-Based Video Summarization Designer
 *  Copyright (C) 2014 Waltenberger Andreas
 *
 *  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 2 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, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package at.ac.tuwien.ims.layout;

import static org.bytedeco.javacpp.opencv_imgproc.CV_INTER_AREA;
import static org.bytedeco.javacpp.opencv_imgproc.cvResize;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;

import org.bytedeco.javacpp.opencv_core.IplImage;

import at.ac.tuwien.ims.ui.KeyframePane;

/**
 * Class which represents an extracted Keyframe from the video
 * Stores the original Frame for scaling purposes and displays a scaled down version for drag and drop interaction
 * @author Andi
 *
 */
public class Keyframe extends ImageView {

	private Image raw;

	public Keyframe(IplImage raw, KeyframePane pane) {
		this.raw = SwingFXUtils.toFXImage(raw.getBufferedImage(), null);

		// create a scaled down version with a width of 400px to display in the UI
		double factor = raw.width() / 400.0;
		IplImage scaled = IplImage.create(400, (int) (raw.height() / factor), raw.depth(), raw.nChannels());
		cvResize(raw, scaled, CV_INTER_AREA);
		setImage(SwingFXUtils.toFXImage(scaled.getBufferedImage(), null));

		// bind the width to the ScrollPane so the image gets resized
		fitWidthProperty().bind(pane.widthProperty());
		setPreserveRatio(true);

		// Keyframes are used to start a drag and drop action
		setOnDragDetected(new EventHandler<MouseEvent>() {
			public void handle(MouseEvent event) {
				Dragboard db = startDragAndDrop(TransferMode.COPY);
				ClipboardContent content = new ClipboardContent();
				content.putImage(getRaw());
				db.setContent(content);
				event.consume();
			}
		});
	}

	public Image getRaw() {
		return raw;
	}
}
