/*
 * Copyright (C) 2018-2020 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.8.1   First version
    2.9.1   Moved helpfiles under resources
*/

package uk.co.gardennotebook;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;

import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebView;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;

/**
 *  Displays the Help system for the Garden Notebook application.
 * 
 *  @author Andrew Gegg
*	@version	2.8.1
*	@since	2.8.1
 */
final class NotebookHelp extends AnchorPane
{
	private static final Logger LOGGER = LogManager.getLogger();

    @FXML
    private WebView webView;
    
	@FXML
	private ResourceBundle resources;
    
    private final String pageId;
    private final String anchorId;
    
    NotebookHelp()
    {
        this(null, null);
    }
    
    NotebookHelp(String pageId, String anchorId)
    {
        this.pageId = (pageId == null) ? "Main" : pageId;
        this.anchorId = anchorId;
        
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/NotebookHelp.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()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("initialize()");
        
        final String pageName = "/helpfiles/" + pageId + ".htm";
        final URL resourceURL = getClass().getResource(pageName);
        if (resourceURL == null)
        {
            LOGGER.debug("cannot find Help page: {}", pageName);
            webView.getEngine().loadContent("<html><body>Cannot find help page '"+pageName+"</body></html>");
            return;
        }
        final String fullURL = resourceURL.toString() + ((anchorId == null) ? "" : "#"+anchorId);
        LOGGER.debug("fullURL: {}", fullURL);
        webView.getEngine().load(fullURL);

        // if the window is just closed (X button, top rhc) the web view keeps running although the window closes
        // to prevent this set the current URL to nothing on exit
        // to catch the exit we need to set the onCloseRequest trap
        // the scene does not exist until initialize() is complete, so we must run later.
        // Easy-peasy! (well, it seems to work...)
        Platform.runLater(() -> {
                    final Preferences prefs = Preferences.userNodeForPackage(GardenNotebook.class).node("help");
                    webView.getScene().getWindow().setHeight(prefs.getDouble("windowHeight", 800));
                    webView.getScene().getWindow().setWidth(prefs.getDouble("windowWidth", 1000));
                    
                    webView.getScene().getWindow().setOnCloseRequest(ex -> {
                            // clear the webEngine, or it might not close down (it might not, anyway)
                            webView.getEngine().load(null);
                            webView.getEngine().getLoadWorker().cancel();
                            // store the window size
                            prefs.putDouble("windowHeight", webView.getScene().getHeight());
                            prefs.putDouble("windowWidth", webView.getScene().getWidth());            
                                                                       } );
                                }
        );
   }
		
}
