/*
 *  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.util;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;

import at.ac.tuwien.ims.Designer;
import at.ac.tuwien.ims.ui.LayoutPane;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * UI element that displays already imported Templates, also makes it possible to delete Templates
 * @author Andreas Waltenberger
 *
 */
public class TemplateChooser extends Stage {

	private BorderPane layout;
	private Scene scene;
	private HBox buttons;
	private ToggleGroup templates;
	private ScrollPane scrollPane;

	private TilePane templatesPane;
	private Button open;
	private Button delete;
	private Button cancel;

	public TemplateChooser(Stage owner, final LayoutPane pane) {
		initOwner(owner);
		initStyle(StageStyle.DECORATED);
		initModality(Modality.WINDOW_MODAL);
		setTitle("Choose or delete a Template");

		templates = new ToggleGroup();

		templatesPane = new TilePane(10, 10);
		templatesPane.setPrefColumns(4);

		scrollPane = new ScrollPane(templatesPane);
		scrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS);
		scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
		scrollPane.setMinSize(910, 428);
		BorderPane.setMargin(scrollPane, new Insets(0, 0, 10, 0));

		readTemplates();

		open = new Button("Open");
		open.setPrefSize(70, 20);
		open.setDefaultButton(true);
		open.disableProperty().bind(templates.selectedToggleProperty().isNull());
		// get the selected Template and open it
		open.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				String id = ((ToggleButton) templates.getSelectedToggle()).getId();
				pane.setContent(new File(Designer.templateDir + File.separator + id + ".xml"));
				close();
			}
		});

		delete = new Button("Delete");
		delete.setPrefSize(70, 20);
		delete.disableProperty().bind(templates.selectedToggleProperty().isNull());
		// delete the preview and the xml file from the Template directory
		delete.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				ToggleButton selection = (ToggleButton) templates.getSelectedToggle();
				String id = selection.getId();

				try {
					for (File f : Designer.templateDir.listFiles()) {
						if (f.getName().split("\\.")[0].equals(id)) {
							Files.delete(f.toPath());
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				templatesPane.getChildren().remove(selection);
				templates.getToggles().remove(selection);
			}
		});

		cancel = new Button("Cancel");
		cancel.setPrefSize(70, 20);
		cancel.setCancelButton(true);
		cancel.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				close();
			}
		});

		buttons = new HBox(10);
		buttons.getChildren().addAll(open, delete, cancel);
		BorderPane.setAlignment(buttons, Pos.BOTTOM_RIGHT);

		layout = new BorderPane();
		layout.setPadding(new Insets(7));
		layout.setCenter(scrollPane);
		layout.setBottom(buttons);

		scene = new Scene(layout);
		setScene(scene);
		sizeToScene();
		setResizable(false);
	}

	private void readTemplates() {
		try {
			// get all preview images to display them in the window
			File[] files = Designer.templateDir.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.endsWith(".png");
				}
			});

			// fill the TilePane with the retrieved preview images
			for (File file : files) {
				ImageView thumbnail = new ImageView(file.toURI().toURL().toString());
				ToggleButton template = new ToggleButton(null, thumbnail);
				template.setId(file.getName().split("\\.")[0]);
				templates.getToggles().add(template);
				templatesPane.getChildren().add(template);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}
