/*
 * @(#)BrowserApiDemo.java	1.13 06/10/30
 * 
 * Copyright (c) 2006 Sun Microsystems, Inc.  All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
 * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
 * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
 * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
 * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
 * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed, licensed or
 * intended for use in the design, construction, operation or
 * maintenance of any nuclear facility. 
 */

/*
 * @(#) BrowserApiDemo.java 1.13 - last change made 10/30/06
 *
 * (c) 1997-1998 Sun Microsystems, Inc.  All rights reserved.  Use is
 * subject to license terms. Sun, Sun Microsystems, the Sun Logo, Solaris,
 * Java, the Java Coffee Cup Logo, and JavaHelp are trademarks or registered
 * trademarks of Sun Microsystems, Inc. in  the U.S. and other countries.
 *
 */

package sunw.demo.browser;

import java.util.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.help.*;
import javax.swing.text.*;
import java.beans.PropertyVetoException;
import javax.swing.*;

/**
 * This class demostrates how to use JavaHelp in a browser
 *
 * @author Roger D. Brinkley
 * @version	1.13	10/30/06
 */

public class BrowserApiDemo extends JApplet implements ActionListener{

    // The Main Help
    String helpsetName = "IdeHelp";
    String helpsetLabel = "demo JDE Help";
    String helpsetURL;
    JFrame helpFrame = null;
    HelpSet mainhs=null;
    HelpBroker mainHB;

    // Auxiliaries
    JRootPane rootpane;
    JPanel top=null;
    JSplitPane split;
    JMenuItem menuItem, menu_help, menu_open;
    JTabbedPane messages;
    int miscTabIndex;

    // Workaround for 1.1.4 compiler bug
    JMenuItem item1;

    // The internal desktop
    JDesktopPane desktop;

    // For the Source JInternalFrame
    JInternalFrame sourceIFrame;

    JButton helpbutton;

    public void init() {
        helpsetName = getParameter("HELPSETNAME");
	System.err.println("helpsetName: " + helpsetName);
	
        helpsetURL = getParameter("HELPSETURL");
	System.err.println("helpsetURL: " + helpsetURL);

	URL url = null;		// for the helpSet
        URL codebase = getCodeBase();
	System.err.println("codeBase: "+codebase);
 
	ClassLoader loader = this.getClass().getClassLoader();
	System.err.println("loader: "+loader);

	if (helpsetURL == null || helpsetURL.equals("")) {
	    url = HelpSet.findHelpSet(loader, helpsetName);
	    System.err.println("url after findHelpSet: "+url);
	} else {
	    try {
		debug ("helpsetURL=" + helpsetURL);
		url = new URL(codebase, helpsetURL);
		System.err.println("url after explicit parameter: "+url);
	    } catch (MalformedURLException e) {
		System.err.println("Malformed URL to HelpSet");
		System.err.println("  codebase: "+codebase);
		System.err.println("  helpsetURL: "+helpsetURL);
		System.exit(1);
	    }
	}

	try {
	    mainhs = new HelpSet(loader, url);
	} catch (Exception ee) {
	    System.out.println ("Help Set "+helpsetName+" not found");
	    ee.printStackTrace();
	    //return;
	}
	mainHB = mainhs.createHelpBroker();

	resources = ResourceBundle.getBundle("sunw.demo.browser.ApiDemo");
        if (resources == null) {
            System.err.println("Resources for application ApiDemo not found");
        }

	rootpane = this.getRootPane();
	mainHB.enableHelpKey(rootpane, "top", null);

	top = new JPanel();
	top.setLayout(new BorderLayout());
	
	JPanel header=new JPanel();
	header.setLayout(new BorderLayout());
	header.add(createMenus(),"North");
	header.add(createToolbar(),"South");

	top.add(header,"North");

	desktop = new JDesktopPane();
	desktop.setOpaque(true);
	desktop.setDoubleBuffered(true);

	createSourceIFrame();
	desktop.add(sourceIFrame, JLayeredPane.PALETTE_LAYER);	

	JPanel panel=new JPanel();
	panel.setLayout(new BorderLayout());
	messages=new JTabbedPane();
	
	JTextArea newtext=new JTextArea();
	newtext.setBackground(Color.white);
	CSH.setHelpIDString(newtext, "build.build");
	messages.addTab("Build", newtext);
	newtext = new JTextArea();
	CSH.setHelpIDString(newtext, "debug.overview");
	messages.addTab("Debug", newtext);
	newtext = new JTextArea();
	CSH.setHelpIDString(newtext, "browse.strings");
	messages.addTab("String Search", newtext);
	miscTabIndex = messages.getTabCount();
	messages.insertTab("Misc", null, new JTextArea(), null, miscTabIndex);

	// Find out when we are selected.  When doing so...

	messages.setSelectedIndex(0);
	messages.setDoubleBuffered(true);
	panel.add(messages,"Center");
	split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,desktop,panel);
	//split.setDoubleBuffered(true);
	split.setOneTouchExpandable(true);

	top.add(split,"Center");

	this.getContentPane().add(top);
    }

    /**
     * Create a JButton out of a resource name
     */
    private JButton createButton(String name) {
	java.net.URL url = this.getClass().getResource(name);
	ImageIcon icon = new ImageIcon(url);
	return new JButton(icon);
    }

    private void createSourceIFrame() {
	if (sourceIFrame != null) {
	    return;
	}

	sourceIFrame = new JInternalFrame("Source", true, true, true, true);
	CSH.setHelpIDString(sourceIFrame, "edit.editsource");
	JComponent c = (JComponent) sourceIFrame.getContentPane();
	c.setLayout(new BorderLayout());
	c.setDoubleBuffered(true);
	sourceIFrame.setDoubleBuffered(true);
	sourceIFrame.setBounds(10,10,550,310);

	JTextArea sourceText = new JTextArea("");       
	sourceText.setFont(new Font("Courier",Font.PLAIN,12));
	sourceText.setBackground(Color.white);

	sourceText.append("/* To view JavaHelp click, Help, Java API Help */"+
		    "\n\nimport java.applet.Applet;"+
		    "\nimport java.awt.Graphics;"+
		    "\n\npublic class HelloWorld extends Applet {"+
		    "\n\n    public void paint(Graphics g) {"+
		    "\n        g.drawString(\"Hello world!\", 50, 25);"+
		    "\n    }\n}\n");

	c.add(sourceText,"Center");
    }

    ResourceBundle resources;

    private JButton addButton(JToolBar toolbar, String img, String tipKey) {
	JButton button = createButton(img);
	if (tipKey != null) {
	    try {
		String tipText =
		    resources.getString("toolbar."+tipKey+".tip");
		button.setToolTipText(tipText);
	    } catch (Exception ex) {
		System.err.println("Could not find a resource for "+tipKey);
	    }
	}
	toolbar.add(button);
	return button;
    }

    public JToolBar createToolbar() {
	JToolBar toolbar=new JToolBar();
	CSH.setHelpIDString(toolbar,"toolbar.main");


	addButton(toolbar, "images/open.gif", "open");
	addButton(toolbar, "images/save.gif", "save");
	toolbar.addSeparator();
	addButton(toolbar, "images/start.gif", "start");
	addButton(toolbar, "images/break.gif", "stop");
	addButton(toolbar, "images/setbreak.gif", "setbreak");
	addButton(toolbar, "images/resume.gif", "resume");
	addButton(toolbar, "images/goto.gif", "goto");
	addButton(toolbar, "images/goend.gif", "goend");
	addButton(toolbar, "images/skip.gif", "skip");
	toolbar.addSeparator();
	addButton(toolbar, "images/down.gif", "down");
	addButton(toolbar, "images/up.gif", "up");
	toolbar.addSeparator();
	helpbutton= addButton(toolbar, "images/help.gif", "help");
	helpbutton.addActionListener(new CSH.DisplayHelpAfterTracking(mainHB));

	return toolbar;
    }

  private JMenuItem addMenuItem(JMenu menu, String label, String tipKey) {
    JMenuItem item = new JMenuItem(label);
    if (tipKey != null) {
	try {
	    String tipText = resources.getString("menu."+tipKey+".tip");
	    item.setToolTipText(tipText);
	 } catch (Exception ex) {
	     System.err.println("Could not find a resource for "+tipKey);
	 }
    }
    menu.add(item);
    return item;
  }

    // An Option Dialog.  Not really good for help

    private void showDialog1() {
	Object options[] = {"OK", "CANCEL", "HELP"};
	int index =
	    JOptionPane.showOptionDialog(null, // parent
					 "Exit?", // message object
					 "Quit", // string title
					 JOptionPane.DEFAULT_OPTION,
					 JOptionPane.QUESTION_MESSAGE,
					 null, // Icon
					 options,
					 options[0]
					 );
	System.err.println("index is: "+index);
	switch (index) {
	case 0:
	    System.exit(0);
	case 1:
	    break;
	case 2:
	    System.err.println("will ask for help");
	    break;
	}
    }

    public JMenuBar createMenus() {
	JMenuBar menuBar = new JMenuBar();
	menuBar.setBackground(getBackground());
	//	menuBar.setOpaque(true);
	JMenu menu = new JMenu("File");
	CSH.setHelpIDString(menu, "menus.file");
	menu.setToolTipText("File operations");
	menuBar.add(menu);
	addMenuItem(menu, "New", "file.new");
	addMenuItem(menu, "Open...", "file.open");
	menu.addSeparator();
	addMenuItem(menu, "Save", "file.save");
	addMenuItem(menu, "Save As...", "file.saveas");

	menu = new JMenu("Edit");
	CSH.setHelpIDString(menu, "menus.edit");
	menuBar.add(menu);
	addMenuItem(menu, "Undo", null);
	addMenuItem(menu, "Redo", null);
	addMenuItem(menu, "Cut", null);
	addMenuItem(menu, "Copy", null);
	addMenuItem(menu, "Paste", null);
	menu.addSeparator();

	menuItem = addMenuItem(menu, "Find", null);
	menuItem.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e){
		JDialog dialog = new FindDialog(BrowserApiDemo.this, null); //  non-modal
		dialog.show();
	    }
	});
	
	menu.addSeparator();
	addMenuItem(menu, "Go to...", null);

       	menu = new JMenu("Build");      
	CSH.setHelpIDString(menu,"menus.build");
	menuBar.add(menu);
	addMenuItem(menu, "Build", null);
	addMenuItem(menu, "Build All", null);
	addMenuItem(menu, "Compile File", null);

	menu = new JMenu("Debug");
	CSH.setHelpIDString(menu,"menus.debug");
	menuBar.add(menu);
	addMenuItem(menu, "Start/Restart", null);
	addMenuItem(menu, "Stop", null);

	menu = new JMenu("Window");
	CSH.setHelpIDString(menu,"menus.windows");
	menuBar.add(menu);

	item1 = menuItem = addMenuItem(menu, "Source", null);
	item1.addActionListener(this);

	JMenu help=new JMenu("Help");
	CSH.setHelpIDString(menu,"menus.help");
	menuBar.add(help);
	menu_help=new JMenuItem(helpsetLabel);
	menu_help.addActionListener(this);
	help.add(menu_help);
	help.addSeparator();

	help.add(new JMenuItem("About..."));
	//	menuBar.setHelpMenu(help);

	return menuBar;
    }

    public void actionPerformed(ActionEvent e) {
	Object source = e.getSource();
	if (source == menu_help) {
	    mainHB.setDisplayed(true);
	} else if (source == item1) {
	    try {
		createSourceIFrame();
		desktop.add(sourceIFrame, JLayeredPane.PALETTE_LAYER);
		sourceIFrame.setIcon(false);
	    } catch (PropertyVetoException ex) {
		// Oh well, ignore
	    }
	}	
    }
    
    /**
     * For printf debugging.
     */
    private final static boolean debug = false;
    private static void debug(String str) {
        if (debug) {
            System.out.println("BroserApiDemo: " + str);
        }
    }
}

class FindDialog extends JDialog {
    private JButton helpButton;
    private JButton closeButton;
    private JFrame frame;
    private BrowserApiDemo demo;

    private void initComponents() {

	// playing with Boxes
	Box topBox = Box.createVerticalBox();

	Box box1 = Box.createHorizontalBox();
	JLabel findLabel = new JLabel("Find: ");
	JTextField textField = new JTextField(20);
	box1.add(Box.createHorizontalStrut(5));
	box1.add(findLabel);
	box1.add(textField);
	box1.add(Box.createHorizontalStrut(5));

	topBox.add(Box.createVerticalStrut(5));
	topBox.add(box1);

	Box box3 = Box.createHorizontalBox();
	box3.add(Box.createHorizontalGlue());
	JButton findButton = new JButton("Find Next");
	JButton prevButton = new JButton("Find Previous");
	box3.add(findButton);
	box3.add(Box.createHorizontalStrut(10));
	box3.add(prevButton);
	box3.add(Box.createHorizontalGlue());

	topBox.add(box3);
	    
	Box box4 = Box.createHorizontalBox();
	Box box5 = Box.createHorizontalBox();

	JCheckBox backwardsCheck = new JCheckBox("Find Backward");
	JCheckBox ignoreCaseCheck = new JCheckBox("Ignore Case");

	box4.add(Box.createHorizontalGlue());
	box4.add(backwardsCheck);
	box4.add(Box.createHorizontalGlue());

	box5.add(Box.createHorizontalGlue());
	box5.add(ignoreCaseCheck);
	box5.add(Box.createHorizontalGlue());

	topBox.add(box4);
	topBox.add(box5);

	Box box2 = Box.createHorizontalBox();
	closeButton = new JButton("Close");
	helpButton = new JButton("Help");

	box2.add(closeButton);
	box2.add(helpButton);

	Box box6 = Box.createHorizontalBox();
	box6.add(Box.createHorizontalStrut(5));
	box6.add(new JSeparator());
	box6.add(Box.createHorizontalStrut(5));

	topBox.add(Box.createVerticalStrut(10));
	topBox.add(box6);
	topBox.add(box2);
	getContentPane().add(topBox);
    }

    public FindDialog(BrowserApiDemo demo, JFrame f) {
	super(f, "Find", false);
	this.frame = f;
	this.demo = demo;
	initComponents();
	pack();

	closeButton.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		setVisible(false);
		dispose();
	    }
	});
	demo.mainHB.enableHelp(helpButton, "browse.strings", null);
	placeDialog();

	show();
    }

    protected void placeDialog() {
	if (frame != null) {
	    int x = frame.getLocation().x + 30;
	    int y = frame.getLocation().y + 100;
	    setLocation(x, y);
	}
    }

}
