/**
* HelpViewer.java - HTML Help viewer
* Copyright (C) 1999, 2000 Slava Pestov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
* jEdit's HTML viewer. It uses a Swing JEditorPane to display the HTML,
* and implements a URL history.
* @author Slava Pestov with modification by Nathan Stevens
* @version 1.22 6/25/05
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.net.*;

public class HelpViewer extends JFrame implements ActionListener {
  private static final String TITLE = "InstruView Help";
  
  // private data members
  private InstruView instruView = null;
  private JEditorPane viewer = null;
  private JFileChooser chooser = null;
  private JTextField urlField = null;
  private URL[] history = null;
  private int historyPos = 0;
  
  // Method that called when this is being used as the help file viewer
  public HelpViewer(InstruView instruView) {
    this(instruView, TITLE);
  }  
  
  // main constructor
  public HelpViewer(InstruView instruView, String title) {
    super(title);
    this.instruView = instruView;
    
    // close this window
		addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
				setVisible(false);
		  }
		});
    
    history = new URL[25]; // hold our history
    
    // The main GUI components
    JPanel panel;
    JLabel label;
    JButton button;
    ImageIcon icon;
    
    panel = new JPanel(new BorderLayout());
    
    icon = new ImageIcon(instruView.imageDirectory + "domtreeviewer.png");
    label = new JLabel("URL ");
    label.setIcon(icon);
    panel.add(label, "West");
    
    urlField = new JTextField();
    urlField.addActionListener(this);
    urlField.setActionCommand("go");
    panel.add(urlField, "Center");
    
    getContentPane().add(BorderLayout.NORTH, panel);
    
    viewer = new JEditorPane();
    viewer.setEditable(false);
    viewer.addHyperlinkListener(new LinkHandler());
    getContentPane().add(BorderLayout.CENTER,
    new JScrollPane(viewer));
    
    panel = new JPanel();
    
    icon = new ImageIcon(instruView.imageDirectory + "1leftarrow.png");
    button = new JButton("Back");
    button.setIcon(icon);
    button.addActionListener(this);
    button.setActionCommand("back");
    panel.add(button);
    
    icon = new ImageIcon(instruView.imageDirectory + "1rightarrow.png");
    button = new JButton("Forward");
    button.setIcon(icon);
    button.addActionListener(this);
    button.setActionCommand("forward");
    panel.add(button);
    
    icon = new ImageIcon(instruView.imageDirectory + "gohome.png");
    button = new JButton("TOC");
    button.setIcon(icon);
    button.addActionListener(this);
    button.setActionCommand("toc");
    panel.add(button);
    
    /*icon = new ImageIcon(instruView.imageDirectory + "Folder.gif");
    button = new JButton("Open");
    button.setIcon(icon);
    button.addActionListener(this);
    button.setActionCommand("open");
    panel.add(button);*/
    
    icon = new ImageIcon(instruView.imageDirectory + "button_cancel.png");
    button = new JButton("Close");
    button.setIcon(icon);
    button.addActionListener(this);
    button.setActionCommand("close");
    panel.add(button);
    
    getContentPane().add(BorderLayout.SOUTH, panel);
    
    // go to the main page now
    showTableOfContents(true);
  }
  
  // Method to handel the action events
  public void actionPerformed(ActionEvent ae) {
    String cmd = ae.getActionCommand();
    if(cmd.equals("back")) {
      if(historyPos <= 1)
        getToolkit().beep();
      else {
        URL url = history[--historyPos - 1];
        gotoURL(url, false);
      }
    }
    else if(cmd.equals("forward")) {
	    if(history.length - historyPos <= 1)
        getToolkit().beep();
	    else {
        URL url = history[historyPos];
        if(url == null)
          getToolkit().beep();
        else {
          historyPos++;
          gotoURL(url,false);
        }
	    }	    
    }
    else if(cmd.equals("toc")) {
	    showTableOfContents(false);
    }
    else if(cmd.equals("open")) {
	    openLocalFile();
    }
    else if(cmd.equals("close")) {
	    setVisible(false);
      dispose();
    }
    else if(cmd.equals("go")) {
	    getURL();
    }
    else {
	    // debug code
      System.err.println("Event not handel in HelpViewer class " + cmd);
    }
  }
  
  /**
  * Displays the specified URL in the HTML component.
  * @param url The URL
  * @param addToHistory Should the URL be added to the back/forward
  * history?
  */
  public void gotoURL(URL url, boolean addToHistory) {
    // reset default cursor so that the hand cursor doesn't
    // stick around
    viewer.setCursor(Cursor.getDefaultCursor());
    
    try {
      urlField.setText(url.toString());
      viewer.setPage(url);
      if(addToHistory) {
        history[historyPos++] = url;
        if(history.length == historyPos) {
          System.arraycopy(history,1,history,
          0,history.length);
          history[historyPos] = null;
        }
      }
    }
    catch(IOException ioe) {
      System.err.println(ioe.toString());
    }
  }
  
  // Method to get and go to the url in the urltext field
  private void getURL() {
    try {
	    gotoURL(new URL(urlField.getText()),  true);
    }
    catch(MalformedURLException mu) {
	    String badurl = urlField.getText();
      System.err.println(mu.toString() + " " + badurl);
    }
  }
  
  // Method to show the table of contents
  public void showTableOfContents(boolean addtohistory) {
    try {
      String tocname = new String("file:" + instruView.homeDirectoryName
      + "docs/index.html");
	    URL toc  = new URL(tocname);
	    gotoURL(toc, addtohistory);
    }
    catch(MalformedURLException mu) {
      System.err.println(mu.toString());
    }
  }
  
  // Method to go a specific file
  private void openLocalFile() {
    chooser = new JFileChooser();
    chooser.showOpenDialog(this);
    
    File tempFile = chooser.getSelectedFile();
    if(tempFile != null) {
	    if(tempFile.isFile()) {
        try {
          String urlname = "file:" + tempFile.toString();
          URL urlfile  = new URL(urlname);
          gotoURL(urlfile, true);
        }
        catch(MalformedURLException mu) {
          System.err.println(mu.toString());
        }
	    }
    }
  }
  
  /*class ActionHandler implements ActionListener
  {
    public void actionPerformed(ActionEvent evt)
    {
      Object source = evt.getSource();
      if(source == back)
      {
        if(historyPos <= 1)
          getToolkit().beep();
        else
        {
          URL url = history[--historyPos - 1];
          gotoURL(url,false);
        }
      }
      else if(source == forward)
      {
        if(history.length - historyPos <= 1)
          getToolkit().beep();
        else
        {
          URL url = history[historyPos];
          if(url == null)
            getToolkit().beep();
          else
          {
            historyPos++;
            gotoURL(url,false);
          }
        }
      }
    }
  }
  
  class KeyHandler extends KeyAdapter
  {
    public void keyPressed(KeyEvent evt)
    {
      if(evt.getKeyCode() == KeyEvent.VK_ENTER)
      {
        try
        {
          gotoURL(new URL(urlField.getText()),
          true);
        }
        catch(MalformedURLException mu)
        {
          Log.log(Log.ERROR,this,mu);
          String[] args = { urlField.getText() };
          GUIUtilities.error(HelpViewer.this,
          "badurl",args);
        }
      }
    }
  } */
  
  /**
  * class that handels different links in html pages
  */
  class LinkHandler implements HyperlinkListener {
    public void hyperlinkUpdate(HyperlinkEvent evt) {
	    if(evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        if(evt instanceof HTMLFrameHyperlinkEvent) {
          ((HTMLDocument)viewer.getDocument())
          .processHTMLFrameHyperlinkEvent(
          (HTMLFrameHyperlinkEvent)evt);
        }
        else {
          URL url = evt.getURL();
          if(url != null) {
            gotoURL(url,true);
          }
        }
	    }
	    else if (evt.getEventType() == HyperlinkEvent.EventType.ENTERED) {
        viewer.setCursor(Cursor.getPredefinedCursor
        (Cursor.HAND_CURSOR));
	    }
	    else if (evt.getEventType() == HyperlinkEvent.EventType.EXITED) {
        viewer.setCursor(Cursor.getDefaultCursor());
	    }
    }
  }
} //--end class HelpViewer
