/*
** FILE:   oh_HtmlHelpFrame.java
**
** (c) 1998 Steve Withall.
**
** HISTORY:
**    30Jul98  stevew  Created, based on xt_HtmlEditFrame, with code from
**                      the Swing HtmlPanel example.
*/
package oh;

import xu.xu_Frame;
import xu.xu_MenuItem;

import xm.xm_StatusBar;

import xg.xg_AttList;

import eh.eh_Debug;

import com.sun.java.swing.text.Document;

import com.sun.java.swing.event.HyperlinkEvent;
import com.sun.java.swing.event.HyperlinkListener;

import com.sun.java.swing.AbstractAction;
import com.sun.java.swing.Action;
import com.sun.java.swing.JEditorPane;
import com.sun.java.swing.JFrame;
import com.sun.java.swing.JPanel;
import com.sun.java.swing.JScrollPane;
import com.sun.java.swing.JViewport;
import com.sun.java.swing.SwingUtilities;

import java.awt.event.ActionEvent;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Toolkit;

//import com.sun.java.accessibility.*;

import java.net.URL;
import java.net.MalformedURLException;

import java.io.FileNotFoundException;
import java.io.IOException;

//*****************************************************************************
/** oh_HtmlHelpFrame is an internal frame containing just a text area for the
 *  display of an HTML page.
 */
public class oh_HtmlHelpFrame extends    xu_Frame
                              implements HyperlinkListener
{
    /** The frame from which this class has been invoked. */
    JFrame       ParentFrame          = null;

    /** The URL of the page currently being displayed. */
    String       CurrentPageUrlString = null;

    /** The HTML view area itself. */
    JEditorPane  HtmlViewPane         = null;

	URL          NewUrl;

    /** A 'wait' cursor is displayed while HTML pages are being loaded. This is
     *  a holding area for the cursor being displayed prior to the load, so that
     *  it can be restored afterwards. */
	Cursor       NormalCursor;

    // Actions. Note that a couple of actions are inherited from xu_Frame.
	HelpAction   TheHelpAction  = new HelpAction();

    //*****************************************************************************
    /** Constructor.
     */
    public oh_HtmlHelpFrame(JFrame  InputParentFrame,
                            String  InputFrameTitle,
                            String  InputCurrentPageUrlString)
    {
        super(InputParentFrame);
	    eh_Debug.add(6, "oh_HtmlHelpFrame: Display HTML page '"
                                      + InputCurrentPageUrlString + "'");  //TEMP
        ParentFrame          = InputParentFrame;
        CurrentPageUrlString = InputCurrentPageUrlString;

//    	getAccessibleContext().setAccessibleName("HTML panel");
//    	getAccessibleContext().setAccessibleDescription("A panel for viewing HTML documents, and following their links");

        loadConfig("config.oh.oh_HtmlHelp");  // Load configuration values,
                                              //  including supported actions
    	// Set frame title and image icon.
    	BasicFrameTitle = "Help - " + InputFrameTitle;
    	setTitle(BasicFrameTitle);
	    setIconImage(TheFrameConfigManager.getFrameIconImage() );

	    getContentPane().setLayout(new BorderLayout() );

        initControlPanel();  // Create menu bar and toolbar

    	MainStatusBar = new xm_StatusBar();
    	getContentPane().add("South", MainStatusBar);

	    pack();

        Toolkit    DefaultToolkit = Toolkit.getDefaultToolkit();
        Dimension  ScreenSize     = DefaultToolkit.getScreenSize();
        setBounds(30, 60, ScreenSize.width - 60, ScreenSize.height - 100);

        URL  url = null;
    	try
        {
    	    url = new URL(CurrentPageUrlString);
//    	    url = new URL("file:" + CurrentPageUrlString);
    	}
        catch (MalformedURLException  InputException)
        {
    	    eh_Debug.add(2, "Malformed URL creating HTML edit frame: " + InputException);
	    }

	    Container  MainContentPane = getContentPane();

	    // Initialise the HTML viewer JEditorPane.
    	try
        {
    	    HtmlViewPane = new JEditorPane(url);
    	}
        catch (IOException  InputException)
        {
    	    eh_Debug.add(2, "IOException creating HTML edit frame: " + InputException);
    	}
    	HtmlViewPane.setEditable(false);
    	HtmlViewPane.addHyperlinkListener(this);
	    HtmlViewPane.setBorder(null);
        HtmlViewPane.requestFocus();

        // Scroller.
    	JScrollPane  EditScrollPane = new JScrollPane();
    	JViewport    EditViewport   = EditScrollPane.getViewport();
    	EditViewport.add(HtmlViewPane);
   	    EditViewport.setBackingStoreEnabled(false);

    	JPanel       EditPanel = new JPanel();
    	EditPanel.setLayout(new BorderLayout());
    	EditPanel.add("Center", EditScrollPane);
    	MainContentPane.add("Center", EditPanel);

	    show();
    }

    //*****************************************************************************
    /** Register the actions supported by this frame.
     */
    protected void registerActions()
    {
        super.registerActions();

    	// Register individual actions.
	    TheFrameConfigManager.registerAction(TheHelpAction);
    }

    //*****************************************************************************
    /** Follow the reference in a link. The given url is the requested reference.
     *  By default this calls <a href="#setPage">setPage</a>, and if an exception
     *  is thrown the original previous document is restored and a beep sounded.
     *  If an attempt was made to follow a link, but it represented a malformed
     *  url, this method will be called with a null argument.
     *
     *  @param  InputNewUrl  the URL to follow
     */
    protected void goToPage(URL  InputNewUrl)
    {
        MainStatusBar.setText("Go to link '" + InputNewUrl + "'");
    	Cursor NormalCursor = HtmlViewPane.getCursor();
    	Cursor WaitCursor   = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
    	HtmlViewPane.setCursor(WaitCursor);
    	SwingUtilities.invokeLater(new PageLoader(InputNewUrl, NormalCursor));
    }

    //*****************************************************************************
    //*HyperlinkListener*method****************************************************
    //*****************************************************************************
    /** Notification of a change relative to a hyperlink.
     */
    public void hyperlinkUpdate(HyperlinkEvent  InputHyperlinkEvent)
    {
	    if (InputHyperlinkEvent.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
	        goToPage(InputHyperlinkEvent.getURL());
    }

    //*****************************************************************************
    /** Temporary class that loads synchronously (although later than the request
     *  so that a cursor change can be done).
     */
    class PageLoader implements Runnable
    {
        //*****************************************************************************
	    PageLoader(URL  InputNewUrl, Cursor  InputNormalCursor)
        {
    	    NewUrl       = InputNewUrl;
    	    NormalCursor = InputNormalCursor;
    	}

        //*****************************************************************************
        public void run()
        {
	        if (NewUrl == null)
            {
        		// Restore the original cursor
        		HtmlViewPane.setCursor(NormalCursor);

        		// PENDING(prinz) remove this hack when automatic validation is activated.
        		Container parent = HtmlViewPane.getParent();
        		parent.repaint();
    	    }
            else
            {
        		Document  HtmlDocument = HtmlViewPane.getDocument();
        		try
                {
        		    HtmlViewPane.setPage(NewUrl);
        		}
                catch (FileNotFoundException  InputException)
                {
        		    HtmlViewPane.setDocument(HtmlDocument);  // Restore good page
                    MainStatusBar.setText("Cannot find HTML page '" + NewUrl + "'");
        		}
                catch (IOException  InputException)
                {
        		    HtmlViewPane.setDocument(HtmlDocument);  // Restore good page
                    MainStatusBar.setText("Error loading HTML page: " + InputException);
        		}
                finally
                {
        		    // Schedule the cursor to revert after the paint has happened.
        		    NewUrl = null;
        		    SwingUtilities.invokeLater(this);
        		}
    	    }
    	}
    }

    //*****************************************************************************
    /** <p>An action which requests display of a new page in the HTML help frame.
     *  It obtains information about the page to display from the attributes
     *  associated with the menu item which invoked it (if it was invoked from an
     *  xu_MenuItem, that is).</p>
     *
     *  <p>The standard oh_HelpAction cannot be used for this purpose, because it
     *  would create a new HTML frame - and we just want to go to a new page in the
     *  existing one.</p>
     *
     *  <p>(The structure could be improved by having this and oh_HelpAction
     *  derive from a common base class.)</p>
     */
    public class HelpAction extends AbstractAction
    {
        //*****************************************************************************
        /** Constructor.
         *
         *  @param InputActionName  The name of the action
         */
        public HelpAction()
        {
        	super("help");
        }

        //*****************************************************************************
        /** We have been invoked!
         */
        public void actionPerformed(ActionEvent  InputActionEvent)
        {
            Object  SourceObject = InputActionEvent.getSource();
            if (SourceObject instanceof xu_MenuItem)
                actionFromMenuItem((xu_MenuItem)SourceObject);
            else
                eh_Debug.add(2, "oh_HelpAction.actionPerformed: Not invoked from an xu_MenuItem,"
                                      + " so cannot obtain attribute list required");
        }

        //*****************************************************************************
        /** We have been invoked from an xu_MenuItem.
         */
        public void actionFromMenuItem(xu_MenuItem  InputMenuItem)
        {
            xg_AttList  MenuItemAttList   = InputMenuItem.getAttList();

            String      HelpFrameTitle    = MenuItemAttList.getAttributeValue("Label");
            //TBD Add error handling
            String      NextPageUrlString = MenuItemAttList.getAttributeValue("Href");
            //TBD Add error handling

    	    BasicFrameTitle = "Help - " + HelpFrameTitle;
    	    setTitle(BasicFrameTitle);

            URL  url = null;
    	    try
            {
    	        url = new URL(NextPageUrlString);
//    	        url = new URL("file:" + NextPageUrlString);
    	    }
            catch (MalformedURLException  InputException)
            {
    	        eh_Debug.add(2, "Malformed URL: " + InputException);
	        }
            goToPage(url);
        }
    }
}

//*****************************************************************************

