/**
 *  Licensed under GPL. For more information, see
 *    http://jaxodraw.sourceforge.net/license.html
 *  or the LICENSE file in the jaxodraw distribution.
 */
package net.sf.jaxodraw.gui.launch;

import java.awt.EventQueue;

import net.sf.jaxodraw.gui.panel.JaxoMainPanel;
import net.sf.jaxodraw.util.JaxoInfo;

/**
 * Launches the JaxoDraw GUI.
 *
 * @since 2.0
 */
public class JaxoLauncher {
    private String[] fileNames = null;

    private static JaxoShutDown shutdownHook = null;

    /**
     * Sets a list of files (absolute path strings) to be opened at start-up.
     *
     * @param files a List of Strings.
     */
    public void setFilesToOpen(final String[] files) {
        this.fileNames = files.clone();
    }

    /**
     * Sets a shutdown hook that will be called from the main panel at shutdown.
     *
     * @param shutdown a JaxoShutDown.
     */
    public void setShutDownHook(final JaxoShutDown shutdown) {
        shutdownHook = shutdown;
    }

    /**
     * Launches the JaxoDraw GUI.
     *
     * @param showSplashWindow whether to show the SplashWindow.
     */
    public void launch(final boolean showSplashWindow) {
        if (showSplashWindow) {
            // Use a (somehow) different title than the main frame. Otherwise
            // the main frame will be numbered (2) with some window managers.
            final JaxoSplashWindow sw = new JaxoSplashWindow(JaxoInfo.VERSION + " ");

            sw.start();

            try {
                sw.waitUntilPainted(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        final JaxoMainPanel main = new JaxoMainPanel(fileNames);

                        main.pack();
                        main.setVisible(true);

                        sw.dispose(2000);
                    }
                });
        } else {
            EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        final JaxoMainPanel main = new JaxoMainPanel(fileNames);

                        main.pack();
                        main.setVisible(true);
                    }
                });
        }
    }

    /**
     * Initiates the shutdown procedure via the registered JaxoShutDown handler.
     * This is called from the MainPanel after the GUI has disposed itself.
     *
     * @param status The exit status code.
     */
    public static void shutdown(final int status) {
        if (shutdownHook != null) {
            shutdownHook.shutdown(status);
        }
    }

}
