/*
 * Copyright (C) 2018-2020, 2023 Andrew Gegg
 
 *
 *	This file is part of the Garden Notebook application
 *
 * The Garden Notebook application 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/gpl.html>.
 */

/*
	Change log
	2.4.0   Use version string embedded in GardenNotebook class
    2.9.0   Catch 'close by top right button' and store the window dimensions
    3.0.3	Add a fade-out
    3.1.1	Pre-load PlantVarieties
 */

package uk.co.gardennotebook;

import java.io.IOException;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;

import javafx.animation.FadeTransition;
//import javafx.animation.ScaleTransition;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import static uk.co.gardennotebook.GardenNotebook.NOTEBOOK_VERSION;

import javafx.util.Duration;
import uk.co.gardennotebook.fxbean.*;
import uk.co.gardennotebook.spi.GNDBException;

/**
 * Splash page shown on entry.
 * Preloads various database tables into the cache
 *
 * @author Andrew Gegg
*	@version	3.1.1
*	@since	1.0
 */
final class GardenSplash extends AnchorPane
{
	@FXML
	private ImageView splashImage;
	private FadeTransition fadeOut;

	@FXML
	private ResourceBundle resources;

	GardenSplash()
	{
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/GardenSplash.fxml"),
			ResourceBundle.getBundle("notebook") );
		fxmlLoader.setRoot(this);
		fxmlLoader.setController(this);
		try {
			fxmlLoader.load();	// NB initialize is called from in here
		} catch (IOException exception) {
			throw new RuntimeException(exception);
		}
	}

	/**
	 * Initializes the controller class.
	 */
	@FXML
	public void initialize()
	{
        setCursor(Cursor.WAIT);
		splashImage.setImage(new Image(GardenNotebook.class.getResource("/Splash.png").toExternalForm()));

		fadeOut = new FadeTransition(Duration.seconds(1.0), splashImage);
		fadeOut.setFromValue(1);
		fadeOut.setToValue(0.2);
		fadeOut.setCycleCount(1);
		/*
		* The scene (i.e. all the contents of the window, here just the Splash image)
		* is not fully constructed and displayed until the constructor is complete - 
		* this is because the stage and scene are actually set in the CALLING class.
		* This method is called sometime in the constructor so, to get any work done,
		* the work must be placed into a separate thread.  When the work is complete
		* the next (i.e. main GUI) class must be displayed.  That display must happen on the
		* JavaFXApplication thread so Platform.runLater() must be used.
		* Not quite true - the internal plumbing in Task makes sure that onSucceeded runs on the application thread.
		*/
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() throws Exception {
//				System.out.println("about to load stuff");
				loadStuff();
//				System.out.println("stuff loaded");
				Thread.sleep(1000);	//	give people chance to read it!
                return null;
            }

        };

		task.setOnSucceeded(e -> showMain());
        new Thread(task).start();
	}
	
	private void loadStuff()
	{
		try {
//			ToDoListBean.fetchAll();	//	TopController does this and the SQL does not check for a pre-loaded list.
//			PlantSpeciesBean.fetchAll();
			PlantSpeciesBean.forceLoad();
			PlantVarietyBean.forceLoad();
			HusbandryClassBean.fetchAll();
			GroundworkActivityBean.fetchAll();
			RetailerBean.fetchAll();
			LocationBean.fetchAll();
		} catch (GNDBException ex) {
			Platform.runLater(() -> PanicHandler.panic(ex));
		}
	}
	
	private void showMain()
	{
        Parent root = null;
		try {
			root = FXMLLoader.load(
				getClass().getResource("/fxml/Top.fxml"),
				resources);
		} catch (IOException ex) {
			Platform.runLater(() -> PanicHandler.panic(ex));
		}
		final Scene scene = new Scene(root);
		final Stage stage = new Stage();

		stage.getIcons().add(new Image(GardenNotebook.class.getResource("/Icon16.png").toExternalForm()));
		stage.getIcons().add(new Image(GardenNotebook.class.getResource("/Icon32.png").toExternalForm()));
		stage.getIcons().add(new Image(GardenNotebook.class.getResource("/Icon64.png").toExternalForm()));
		stage.setTitle(String.format(resources.getString("app.title"), NOTEBOOK_VERSION));  //  2.4.0
		stage.setScene(scene);
		final Preferences prefs = Preferences.userNodeForPackage(GardenNotebook.class);
		stage.setHeight(prefs.getDouble("windowHeight", 800));
		stage.setWidth(prefs.getDouble("windowWidth", 1000));
		stage.setOnCloseRequest(ev -> {
				prefs.putDouble("windowHeight", stage.getHeight());
				prefs.putDouble("windowWidth", stage.getWidth());
		});
		//	Finish splash with fade out effect
		fadeOut.setOnFinished(e -> {
			stage.show();
			setCursor(Cursor.DEFAULT);
			this.getScene().getWindow().hide();
//			stage.show();
		});
//		System.out.println("about to fade out");
		fadeOut.play();
	}
	
}
