package testjvmcrash;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Window;
import java.io.File;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.print.PrinterJob;
import javafx.scene.CacheHint;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javax.swing.JFrame;

public class HelpHtml extends JPanel {
    private static final long serialVersionUID = -9041043172614169469L;
    private static HelpHtml instance;
    private WebView webView;

    public static HelpHtml getInstance() {
        if (instance == null) {
            new JFXPanel();
            instance = new HelpHtml();
        }
        return instance;
    }

    public void loadPage(Component owner, String manualPageCode) {
        loadPage(owner, manualPageCode, true);
    }

    public void loadPage(Component owner, String manualPageCode, boolean isManual) {
        // Creation of scene and future interactions with JFXPanel
        // should take place on the JavaFX Application Thread
        Platform.runLater(() -> {
            try {
                JFXPanel jfxPanel = new JFXPanel();

                webView = new WebView();

                webView.setCache(true);
                //webView.setCacheShape(true);
                webView.setCacheHint(CacheHint.SPEED);

                BorderPane root = null;
                File f = null;
                webView.getEngine().setUserStyleSheetLocation(new File("images/css.css").toURI().toURL().toString());

                if (isManual) {

                    TreeItem<String> rootItem = new TreeItem<>("Manual");
                    rootItem.setExpanded(true);

                    TreeItem<String> item = null;
                    TreeItem<String> item1 = null;

                    item = new TreeItem<>("Login");
                    rootItem.getChildren().add(item);

                    item = new TreeItem<>("Management");
                    rootItem.getChildren().add(item);

                    item1 = new TreeItem<>("Active alarm");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Event log");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Alarm log");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Material");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("User");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Settings");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Hardware configuration");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Field control");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("About");
                    item.getChildren().add(item1);

                    item = new TreeItem<>("Layout");
                    rootItem.getChildren().add(item);

                    item1 = new TreeItem<>("Drying");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Loading");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Dosing");
                    item.getChildren().add(item1);

                    item1 = new TreeItem<>("Storage");
                    item.getChildren().add(item1);


                    item = new TreeItem<>("Detail");
                    rootItem.getChildren().add(item);

                    TreeView<String> tree = new TreeView<>(rootItem);

                    tree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> handle(newValue));

                    expandTreeView(rootItem);

                    WebHistory history = webView.getEngine().getHistory();

                    Button backButton = new Button("Back");
                    backButton.disableProperty().bind(history.currentIndexProperty().lessThanOrEqualTo(0));
                    backButton.setOnAction(e -> history.go(-1));

                    Button forwardButton = new Button("Forward");
                    forwardButton.disableProperty().bind(history.currentIndexProperty().greaterThanOrEqualTo(Bindings.size(history.getEntries()).subtract(1)));
                    forwardButton.setOnAction(e -> history.go(1));

                    Button printButton = new Button("Print");
                    printButton.setOnAction(e -> {
                        PrinterJob job = PrinterJob.createPrinterJob();
                        if (job != null && job.showPrintDialog(webView.getScene().getWindow())) {
                            webView.getEngine().print(job);
                            job.endJob();
                        }
                    });

                    HBox controls = new HBox(10, /*homeButton,*/ backButton, forwardButton, printButton);
                    controls.setPadding(new Insets(10));
                    root = new BorderPane(webView, controls, null, null, tree);

                    f = new File("html/en/" + manualPageCode);
                } else {
                    f = new File(manualPageCode);
                    root = new BorderPane(webView, null, null, null, null);
                }
                jfxPanel.setScene(new Scene(root));
                webView.getEngine().load(f.toURI().toURL().toString());

                SwingUtilities.invokeLater(() -> {
                    /*Window window = SwingUtilities.getWindowAncestor(owner);

                    JDialog diag = new JDialog(window);
                    diag.setModal(true);
                    //diag.setIconImage(new ImageIcon("svs_icon.png").getImage());
                    diag.setLayout(new BorderLayout());
                    diag.add(jfxPanel, BorderLayout.CENTER);

                    diag.setSize((int) (window.getWidth() / 1.2), window.getHeight());
                    diag.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    diag.setLocationRelativeTo(window);
                    diag.setVisible(true);*/
                    
                    JFrame frame = new JFrame();
                    
                    frame.setLayout(new BorderLayout());
                    frame.add(jfxPanel, BorderLayout.CENTER);

                    frame.setSize(1200, 700);
                    frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                    frame.setLocationRelativeTo(null);
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.setVisible(true);
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void handle(Object newValue) {
        boolean visible = true;

        switch (((TreeItem<String>) newValue).getValue()) {
            case "Login":
                load("Login.htm");
                break;

            case "Active alarm":
                load("Active alarm.htm");
                break;

            case "Event log":
                load("EventLog.htm");
                break;

            case "Alarm log":
                load("AlarmLog.htm");
                break;

            case "Material":
                load("Material.htm");
                break;

            case "User":
                load("User.htm");
                break;

            case "Settings":
                load("Settings.htm");
                break;

            case "Hardware configuration":
                load("HardwareConfiguration.htm");
                break;

            case "About":
                load("About.htm");
                break;

            case "Field control":
                load("FieldControl.htm");
                break;

            case "Loading":
                load("Layout-Loading.htm");
                break;

            case "Drying":
                load("Layout-Drying.htm");
                break;

            case "Dosing":
                load("Layout-Dosing.htm");
                break;

            case "Storage":
                load("Layout-Storage.htm");
                break;

            default:
                visible = false;
        }
        webView.setVisible(visible);
    }

    private void load(String fileName) {
        //Platform.runLater(() -> {
        try {
            webView.getEngine().load(new File("html/en/" + fileName).toURI().toURL().toString());
        } catch (MalformedURLException ex) {
            Logger.getLogger(HelpHtml.class.getName()).log(Level.SEVERE, null, ex);
        }
        //});
    }

    private void expandTreeView(TreeItem<?> item) {
        if (item != null && !item.isLeaf()) {
            item.setExpanded(true);
            for (TreeItem<?> child : item.getChildren()) {
                expandTreeView(child);
            }
        }
    }
    
    public static void main(String[] args) {
        getInstance().loadPage(null, "Layout-Dosing.htm");
    }
}
