/*
 * Copyright (c) 2002 iReasoning Networks. All Rights Reserved.
 * 
 * This SOURCE CODE FILE, which has been provided by iReasoning Networks as part
 * of an iReasoning Software product for use ONLY by licensed users of the product,
 * includes CONFIDENTIAL and PROPRIETARY information of iReasoning Networks.  
 *
 * USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS 
 * OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
 * THE PRODUCT.
 *
 * IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD IREASONING SOFTWARE, ITS
 * RELATED COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY
 * CLAIMS OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR
 * DISTRIBUTION OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES
 * ARISING OUT OF OR RESULTING FROM THE USE, MODIFICATION, OR
 * DISTRIBUTION OF PROGRAMS OR FILES CREATED FROM, BASED ON, AND/OR
 * DERIVED FROM THIS SOURCE CODE FILE.
 */

package launcher;
import com.ultraswing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.reflect.Method;


/**
 * This class create a main frame for launching demo programs.
 */
public class Launcher 
{
    private static CFrame _frame;
    private static JEditorPane demoSrcPane = null;
    
    private static CFrame createFrame()
    {
        CFrame frame = new CFrame();
        createFrame(frame);
        frame.setSize(800, 600);
        frame.centerOnScreen();
        frame.setVisible(true);
        frame.setExitOnClose();
        return frame;
    }
    
    private static void createFrame(CFrame frame)
    {
        frame.setTitle( "Launcher demo" );
        JMenuBar menuBar = createMenus();
        frame.setJMenuBar( menuBar );
        
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        frame.getContentPane().add( content, BorderLayout.CENTER );

        content.add( createToolBar(), BorderLayout.NORTH);
        content.add(createMainWindow(), BorderLayout.CENTER);

        StatusBar status = new StatusBar( new JComponent[]
                {StatusBar.INDICATOR_STATUS,
                 StatusBar.SEPARATOR,
                 StatusBar.INDICATOR_DATE,
                 StatusBar.SEPARATOR,
                 StatusBar.INDICATOR_TIME,
                 StatusBar.SEPARATOR,
                 StatusBar.INDICATOR_JVM
                 }, true);
        frame.addStatusBar(status);
    }

    public static final int LARGE_ICON = 0;
    public static final int SMALL_ICON = 1;
    public static final int LIST_ICON  = 2;
    public static final int DETAIL_ICON = 3;

    private static CToolBar createToolBar()
    {
        CToolBar toolbar = new CToolBar();
        toolbar.setFloatable(false);
        toolbar.setBorder(null);
        addButton(toolbar, "AutoHide", "dockAndFloat.AutoHide");
        addButton(toolbar, "Docking", "dockAndFloat.Dock");
        addButton(toolbar, "Outlook", "outlook.Outlook");
        addButton(toolbar, "Table", "table.Table");
        addButton(toolbar, "Explorer", "explorer.Explorer");

        return toolbar;
    }

    private static void addButton(CToolBar toolbar, String text, String className)
    {
        DropDownButton dropBtn = new DropDownButton(text);
        dropBtn.setSeparateButton(true);
        JPopupMenu popup = new JPopupMenu();
        dropBtn.setPopupMenu(popup);
        JMenuItem execute = popup.add(new JMenuItem("Run"));
        JMenuItem close = popup.add(new JMenuItem("Stop"));

        dropBtn.addActionListener(new LoadSourceAction(text));
        execute.addActionListener(new ExeAction(className));
        close.addActionListener(new CloseAction(className));
        toolbar.add(dropBtn);
    }

    static class LoadSourceAction implements ActionListener
    {
        private String _btnText;
        public LoadSourceAction(String text)
        {
            _btnText = text;
        }
        public void actionPerformed(ActionEvent e)  
        {
            demoSrcPane.setText("Loading source code ...");
            demoSrcPane.repaint();
            SwingUtilities.invokeLater(new Runnable() 
            {
                public void run() 
                {
                    demoSrcPane.setText(getSourceCode(_btnText));
                    demoSrcPane.setCaretPosition(0);
                }
            });
        }    
    }

    static class ExeAction implements ActionListener
    {
        String c;
        public ExeAction(String className)
        {
            c = className;
        }
        public void actionPerformed(ActionEvent e)  
        {
            execute(c, null);
        }
    }

    static class CloseAction implements ActionListener
    {
        String c;
        public CloseAction(String className)
        {
            c = className;
        }
        public void actionPerformed(ActionEvent e)  
        {
            close(c);
        }
    }

    private static void execute(String className, String[] args)
    {
        try
        {
            if(className.indexOf("Explorer") >= 0)
            {
                try
                {
                    JList.class.getMethod("getLayoutOrientation", null);
                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(null, "Explorer demo reqires JDK1.4+", 
                            "Message",  JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            Class mainClass = null;
            mainClass = Class.forName(className);
    
            Method m = null;
            m = mainClass.getMethod("getFrame", null);
            CFrame f = (CFrame) m.invoke(mainClass, null);
            if(f != null) 
            {
                f.requestFocus();
                return;//already running
            }
            m = mainClass.getMethod("main", new Class[]{String[].class});
    
            m.invoke(mainClass,new Object[]{ args });

            m = mainClass.getMethod("getFrame", null);
            f = (CFrame) m.invoke(mainClass, null);
            f.disableCloseButton();
        }
        catch(Exception e)
        {
            System.out.println( e);
            e.printStackTrace();
        }
    }

    private static void close(String className)
    {
        try
        {
            Class mainClass = Class.forName(className);
            Method m = mainClass.getMethod("getFrame", null);
            CFrame f = (CFrame) m.invoke(mainClass, null);
            if(f != null)
            {
                f.dispose();
                m = mainClass.getMethod("setFrame", new Class[]{CFrame.class});
                Object [] args = new Object[]{null};
                m.invoke(mainClass, args);
            }
        }
        catch(Exception e)
        {
            System.out.println( e);
            e.printStackTrace();
        }
    }

    private static String getSourceCode(String btnText)
    {
        StringBuffer sourceCode = new StringBuffer("<html><body bgcolor=\"#ffffff\"><pre>");
        InputStream is;
        InputStreamReader isr;
        CodeViewer cv = new CodeViewer();
        URL url = null;
        String filename = null;
        if(btnText.startsWith("Explorer"))
        {
            filename = "/explorer/Explorer.java";
        }
        else if(btnText.startsWith("Docking"))
        {
            filename = "/dockAndFloat/Dock.java";
        }
        else if(btnText.startsWith("AutoHide"))
        {
            filename = "/dockAndFloat/AutoHide.java";
        }
        else if(btnText.startsWith("Outlook"))
        {
            filename = "/outlook/Outlook.java";
        }
        else if(btnText.startsWith("Table"))
        {
            filename = "/table/Table.java";
        }

        try 
        {
            url = SwingUtil.class.getResource(filename); 
            is = url.openStream();
            isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);

            String line = reader.readLine();
            while(line != null) 
            {
                sourceCode.append(cv.syntaxHighlight(line) + " \n ");
                line = reader.readLine();
            }
            sourceCode.append("</pre></body></html>");
        }
        catch (Exception ex) 
        {
            sourceCode = new StringBuffer("Could not load file: " + filename );
        }
        return sourceCode.toString();    
    }
    
    private static JScrollPane createMainWindow()
    {
        demoSrcPane = new JEditorPane("text/html", "");
        demoSrcPane.setEditable(false);

        JScrollPane scroller = new JScrollPane();
        scroller.getViewport().add(demoSrcPane);
        return scroller;
    }
 
    /**
     * Create menus
     */
    private static JMenuBar createMenus()
    {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = menuBar.add( new JMenu( "File" ) );
        JMenuItem mi = fileMenu.add( new JMenuItem( "Exit" ) );
        mi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)  
            {
                System.exit(0);
            }
        });
        return menuBar;
    }
    
    public static void main(String[] args)
    {
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e)
        {
            System.out.println( "setLookAndFeel failed ..........................." );
        }
        try
        {
            SplashScreen splash = new SplashScreen("/images/splash.jpg", true);
            splash.setProgressBarColor(Color.gray, Color.blue);
            splash.start();
            for (int i = 0; i < 10 ; i++)
            {
                // do initialization .....
                splash.setProgress(10 * i);//total progress value is 100

                //Add sleep time because there's little to load for this demo, and we don't want splash disappear too quickly
                Thread.sleep(200);
            }
            splash.close();//close splash screen and ready to show main window

            _frame = createFrame();
        }
        catch(Exception e)
        {
            System.out.println( e);
            e.printStackTrace();
        }

    }
}// end of class Launcher