/*
 * ConfigApp.java
 * 
 * Copyright (c) 2003-2004 Digi International
 * This program and the information contained in it is confidential and
 * proprietary to Digi International and may not be used, copied, or re-
 * produced without the prior written permission of Digi International.
 * 
 */
package com.digi.config.ui;

import com.digi.config.util.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;

/**
 * This class is the primary root class of the GUI. This class extends JApplet
 * and can therefore be used as an applet. It also has a main method that allows this
 * class to be used as an application as well. 
 */
public class ConfigApp extends JApplet
{
    /** SocketFactory required when running as a standalone application */
    static HttpsSocketFactory httpsSocketFactory;

    /** Shell frame used when running as a standalone application - holds the splash screen */
    static JFrame shellAppFrame;

    /** The frame holding the main ConfigAppPanel */
    JFrame configAppFrame;

    /** flag indicating if this is being run as an applet or an application */
    boolean appletMode = true;


    /**
     * The entry point when running this program as an application.
     */
    static public void main(String args[]) {
        try {
            // Set our own SSL socket factory. This is done only so that we can use
            // our own trust manager. It is not required in the applet because it uses
            // the Java Plug-In's SSL socket factory and trust manager.
            // See com.digi.config.util.HttpsTrustManager and HttpsSocketFactory for details.
            httpsSocketFactory = new HttpsSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(httpsSocketFactory);
            HttpsURLConnection.setDefaultHostnameVerifier(httpsSocketFactory);

            // Create a new instance of the application frame and make it visible
            shellAppFrame = new JFrame();
            ConfigApp applet = new ConfigApp();
            applet.appletMode = false;
            shellAppFrame.setContentPane(applet);
            applet.init();
            applet.start();

            shellAppFrame.setTitle(ConfigResource.getUiRbString("AppTitle"));
            ImageIcon icon = ConfigResource.getImageRbIcon("logo");
            if (icon!=null) {
                shellAppFrame.setIconImage(icon.getImage());
            }

            shellAppFrame.pack();
            shellAppFrame.setVisible(true);
        } catch (Exception e) {
            System.out.println("Error Initializing Configuration Application: "+e.getMessage());
            e.printStackTrace();  
            // Exit with error condition
            System.exit(1);
        }
    }

    /** 
     * Applet method to initialize the applet. This method places a progress splash screen in the display area
     * and then asynchronously starts construction of the main applet. This construction happens in a background 
     * thread and eventually launches a new frame window holding the config GUI. As construction progresses, updates
     * are made by the background thread to the progress bar in the Splash Screen.
     */
    public void init()
    {
        m_currentApplet = this;
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        // tell the config and help system about the applet
        if (appletMode) {
            PathLocater.setDocumentBase(this.getDocumentBase());
            HelpDisplay.setApplet(this);
        }

        // Specify where to find application msg, ui string, image, and help resources
        ConfigResource.loadMsgTextRb("com.digi.config.resources.ConfigResourceBundle");
        ConfigResource.loadUiTextRb("com.digi.config.resources.ConfigUiResourceBundle");
        ConfigResource.loadUiImageRb("com.digi.config.resources.ConfigImgResourceBundle");
        ConfigResource.loadHelpTextRb("com.digi.config.resources.ConfigHelpResourceBundle");

        try {
            // Display Splash Screen
            System.out.println("Initializing Applet...");
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new SplashScreenPanel(), BorderLayout.CENTER);
            setSize(500, 300);
            setVisible(true);

            // Set Init State
            SplashScreenPanel.currentScreen().updateProgress();

            // Run Init Thread in Background
            InitConfigAppPanelThread init = new InitConfigAppPanelThread();
            init.start();

        } catch (Exception e) {
            System.out.println("Error Initializing Configuration Applet: "+e.getMessage());
            e.printStackTrace();
        }
    }

    class InitConfigAppPanelThread extends Thread {
        InitConfigAppPanelThread() {}

        public void run() {
            try {
                System.out.println("Initializing main GUI in background thread...");            

                // If we are running as an applet, do some special setup
                if (ConfigApp.currentApplet().appletMode) {
                    System.out.println("Initializing applet settings...");            
                    ConfigSettings.setBoolean("General", "AppletMode", true);
                    SplashScreenPanel.currentScreen().updateProgress();

                    // Get some potential applet parameters
                    String developer = getParameter("ConfigDeveloper");
                    if (developer!=null) {
                        System.getProperties().setProperty("ConfigDeveloper", developer);
                    }

                    String timeout = getParameter("ConnectTimeout");
                    if (timeout!=null) {
                        System.getProperties().setProperty("sun.net.client.defaultConnectTimeout", timeout);
                    }

                    URL codeBase = ConfigApp.currentApplet().getCodeBase();

                    String hostName = getParameter("RciHost");
                    if ((hostName==null) || (hostName.trim().length()==0)) {   
                        hostName = codeBase.getHost();
                    }
                    System.getProperties().setProperty("RciHost", hostName);
                    SystemLog.debug("RciHost = "+hostName);

                    String protocol = getParameter("RciProtocol"); // http or https
                    if (protocol==null || protocol.trim().length()==0) {   
                        protocol = codeBase.getProtocol();
                    }
                    System.getProperties().setProperty("RciProtocol", protocol);
                }

                // Construct the Main Panel and store it in the applet
                ConfigApp.currentApplet().setConfigPanel(new ConfigAppPanel(false));
                SplashScreenPanel.currentScreen().updateProgress();
            } catch (Exception e) {
                System.out.println("Error Initializing Configuration Applet: "+e.getMessage());
                e.printStackTrace();
            }

            // Now that UI is constructed, lets trigger a UI callback to activate it.
            Timer initTimer = new Timer(1000, new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    ConfigApp.currentApplet().launchConfigAppFrame();
                }
            });

            initTimer.setRepeats(false);
            initTimer.start();
        }
    }

    /** The ConfigAppPanel associated with this applet */
    protected ConfigAppPanel configPanel;
    public void setConfigPanel(ConfigAppPanel configPanel) {
        this.configPanel = configPanel;
    }

    /** The applet singleton */
    protected static ConfigApp m_currentApplet = null;
    public static ConfigApp currentApplet() { return m_currentApplet; }

    /**
     * Opens the now loaded ConfigAppPanel in a standalone jframe
     */
    protected void launchConfigAppFrame()
    {
        try {
            configAppFrame = new JFrame();
            // set up the applet
            System.out.println("Initializing Interface...");   
            configAppFrame.setTitle(ConfigResource.getUiRbString("AppTitle")+" - "+configPanel.device.getUrlName());
            ImageIcon icon = ConfigResource.getImageRbIcon("logo");
            if (icon!=null) {
                configAppFrame.setIconImage(icon.getImage());
            }
            configAppFrame.getContentPane().removeAll();
            configAppFrame.getContentPane().setLayout(new BorderLayout());
            configAppFrame.getContentPane().add(configPanel, BorderLayout.CENTER);
            int width = ConfigSettings.getInteger("WindowSettings","FrameWidth");
            int height = ConfigSettings.getInteger("WindowSettings","FrameHeight");
            configAppFrame.setSize(new Dimension(width, height));
            configAppFrame.addWindowListener(new WindowAdapter() {
                    /**
                     * Invoked when a window has been closed.
                     */
                    public void windowClosing(WindowEvent e) {
                        System.out.println("Closing browser window");
                        exitApplication();
                    }
                    });
            configAppFrame.setVisible(true);
            
            // Set Final State
            //SplashScreenPanel.currentScreen().updateProgress();
            SplashScreenPanel.currentScreen().finished();
            SplashScreenPanel.currentScreen().showCurrentState();
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            getContentPane().validate();
    
            System.out.println("Running...");
        } catch (Exception e) { 
            System.out.println("Error Initializing Configuration Applet: "+e.getMessage());
            e.printStackTrace();
        }
    }

    protected void exitApplication() {
        if (!appletMode) {
            // Hide the frame
            shellAppFrame.setVisible(false);
            // Free system resources
            shellAppFrame.dispose();
            // Exit the application
            System.exit(0);
        }
    }


}
