/*
 *   GUI application demonstration for exe4j
 */


import com.install4j.api.Util;
import com.install4j.api.launcher.ApplicationLauncher;
import com.install4j.api.launcher.SplashScreen;
import com.install4j.api.launcher.StartupNotification;
import com.install4j.api.launcher.Variables;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Map;

public class HelloGui extends JFrame {

    private JLabel helloLabel;

    private HelloGui() {

        setSize(600, 400);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screenSize.width - 600) / 2, (screenSize.height - 400) / 2);
        setTitle("Hello World GUI");

        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        JMenuItem updateItem = new JMenuItem("Check For Update");
        updateItem.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    checkForUpdate();
                }
            }
        );
        menu.add(updateItem);

        JMenuItem changeNameItem = new JMenuItem("Change Greeting Name (Custom Installer Application)");
        changeNameItem.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    changeName();
                }
            }
        );
        menu.add(changeNameItem);

        menu.addSeparator();

        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.exit(0);
                }
            }
        );

        menu.add(exitItem);

        menuBar.add(menu);
        setJMenuBar(menuBar);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        helloLabel = new JLabel(getGreetingText());
        helloLabel.setFont(helloLabel.getFont().deriveFont(50f));
        helloLabel.setHorizontalAlignment(SwingConstants.CENTER);
        getContentPane().add(helloLabel, BorderLayout.CENTER);


        Box box = Box.createVerticalBox();
        box.add(new JLabel(" * See the \"File\" menu for examples of auto-updaters and custom installer applications"));
        box.add(new JLabel(" * Quit and pass \"fail\" as an argument to hello_gui to see what happens for a startup failure"));
        box.add(new JLabel(" * On Windows: start hello_gui.exe again to see how startup notification works"));
        getContentPane().add(box, BorderLayout.SOUTH);
    }

    private void checkForUpdate() {
        // Here, the "Standalone updater application" is launched in a new process.
        // The ID of the installer application is shown in the install4j IDE on the screens & actions tab
        // when the "Show IDs" toggle button is selected.
        // Use the "Integration wizard" button on the "Launcher integration" tab in the configuration
        // panel of the installer application, to get such a code snippet.
        try {
            ApplicationLauncher.launchApplication("535", null, false, null);
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showConfirmDialog(this, "Could not launch updater.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void changeName() {
        // Here, the "Configure greeting application" is launched in the same process.
        // The ID of the installer application is shown in the install4j IDE on the screens & actions tab
        // when the "Show IDs" toggle button is selected.
        // Use the "Integration wizard" button on the "Launcher integration" tab in the configuration
        // panel of the installer application, to get such a code snippet.
        ApplicationLauncher.launchApplicationInProcess("594", null, new ApplicationLauncher.Callback() {
            public void exited(int exitValue) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        helloLabel.setText(getGreetingText());
                        printToConsole();
                    }
                });
            }

            public void prepareShutdown() {
                // will not be invoked in this case
            }
        }, ApplicationLauncher.WindowMode.DIALOG, this);
    }

    private String getGreetingText() {

        String greetingName = "world";
        try {
            Map variables = Variables.loadFromPreferenceStore(true);
            if (variables != null) {
                greetingName = (String)variables.get("greeting");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "Hello " + greetingName + "!";
    }

    private void printToConsole() {
        if (Util.isWindows()) {
            // In order to see the following output, please start the launcher from a console window
            // with the parameter -console
            //
            // On Windows, GUI applications usually cannot access the console if they were started from a console window
            // Since the "Allow -console parameter" option was selected in the launcher configuration of the
            // hello_gui executable, the console is acquired by the launcher and stdout will be printed to it
            System.out.println(getGreetingText());
            String additionalMessage = System.getProperty("additional.message");
            if (additionalMessage != null) {
                // Print the VM property that is contained in the hello.vmoptions file
                System.out.println(additionalMessage);
            }
        }
    }

    public static void main(String[] args)
        throws Exception
    {

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        try {
            SplashScreen.writeMessage("Initializing giant application ...");
            Thread.sleep(1000);
            SplashScreen.writeMessage("Opening complex main window ...");
            Thread.sleep(1000);
        } catch (SplashScreen.ConnectionException ex) {
        }
        if (args.length == 1 && args[0].equals("fail")) {
			throw new RuntimeException("I was asked to fail");
        } else {
            final HelloGui helloGui = new HelloGui();

            // startup notification on Microsoft Windows
            StartupNotification.registerStartupListener(new StartupNotification.Listener() {
                public void startupPerformed(final String parameters) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(helloGui, "I've been started again, with parameters \"" + parameters +  "\".", "Hello World", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                }
            });

            helloGui.printToConsole();

            helloGui.setVisible(true);
        }
    }

}