import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

// A class that allows one to fetch an HTML file from the web and obtain
// a list of all the links contained within the HTML.
public class HTMLLinkFinder extends JApplet implements ActionListener {

	// Dimensions for HTML display area
	private static final int HTMLWIDTH = 60;
	private static final int HTMLHEIGHT = 20;

	// Dimensions for links display area
	private static final int LINKSWIDTH = 60;
	private static final int LINKSHEIGHT = 10;

	// Large font for GUI controls
	private Font bigFont = new Font("Times", Font.PLAIN, 16);

	// Area in which HTML is displayed
	private JTextArea html;

	// Link display area
	private JTextArea links;

	// Panel for HTML and link displays
	private JPanel textAreaPanel = new JPanel();

	// The "load" button
	private JButton doit;

	// Controls used to specify URL to load + search string
	private JPanel urlChoosers = new JPanel();

	// Url controls
	private JComboBox favorites;
	
	// Label showing what URL we are currently viewing
	private JLabel urlLabel;

	// Set up all GUI controls and their listeners
  	public void init() {
  		Container contentPane = getContentPane();

  		// Create a "bookmarks" menu
		urlChoosers.add( new JLabel("Favorites:"));
 	 	favorites = new JComboBox();
  		favorites.setFont(bigFont);
		favorites.addItem("http://www.cs.pomona.edu/~kim");
		favorites.addItem("http://www.pomona.edu");
		favorites.addItem("http://www.cs.pomona.edu");
 	 	favorites.addItem("http://www.williams.edu/admin-depts/registrar/exams/index.html");
 	 	favorites.addItem("http://www.williams.edu/admin-depts/registrar/catalog/springhours.html");
		favorites.setEditable(true);
 		urlChoosers.add(favorites);

  		contentPane.add(urlChoosers,"North");

		// Create the text areas in which HTML and links will be displayed.
		urlLabel = new JLabel();
		textAreaPanel.add (urlLabel);
	  	html = new JTextArea(HTMLHEIGHT,HTMLWIDTH);
  		html.setFont(bigFont);
  		JScrollPane htmlScroller = new JScrollPane (html);
   		textAreaPanel.add(htmlScroller);

 	 	links = new JTextArea(LINKSHEIGHT,LINKSWIDTH);
 	 	links.setFont(bigFont);
 	 	JScrollPane linksScroller = new JScrollPane (links);
  	 	textAreaPanel.add(linksScroller);

	  	contentPane.add(textAreaPanel,"Center");

  		// Create the button used to start fetching a web page
	  	doit = new JButton("Fetch HTML");
 	 	doit.setFont(bigFont);
 	 	doit.addActionListener(this);
 	 	contentPane.add(doit,"South");
 	 	
		validate();
  	}

	// When the "Fetch" button is pressed, try to get the HTML, display and search it.
	public void actionPerformed(ActionEvent e) {
		String fullpage;
		String url;

		// If text is selected in the links area, try to use that as a link.  Otherwise,
		// use the current setting of the favorites menu.
		if ( links.getSelectedText() != null) {
			url = links.getSelectedText().trim();
		}
		else {
			url = favorites.getSelectedItem().toString();
		}

		try {
			// Get and display the web page and its links
			fullpage = getWebPage( url );
			urlLabel.setText(url.toString());
			html.setText(fullpage);
			links.setText( findLinks( fullpage ) );
		} catch (MalformedURLException ex){
			JOptionPane.showMessageDialog (html, "Bad URL: " + ex.getMessage());
		} catch (IOException ex){
			JOptionPane.showMessageDialog (html, "Can't get web page: " 
					+ ex.getMessage());
		}
	}

	// Fetch the web page at "url" and return its contents as a String.
	// Throws MalformedURLException if the url has the wrong syntax.
	// Throws IOException for any other problems getting the web page.
	private String getWebPage(String urlString)
		throws MalformedURLException, IOException 
		{
	  	URL url = new URL (urlString);

		StringBuffer buildpage = new StringBuffer();

		// Create the BufferedReader so we can read a line at a time
		BufferedReader pageReader = new BufferedReader(
					new InputStreamReader(url.openStream()));
		String nextLine = pageReader.readLine();
		while (nextLine != null) {
			buildpage.append(nextLine + "\n");
			nextLine = pageReader.readLine();
		}
		pageReader.close();
     	return new String(buildpage);
 	}


  	// Extract all the links from a web page
 	private String findLinks( String fullpage ) {

    	int tagPos,		// Start of <A tag specification
          tagEnd;		// Position of first ">" after tag start

      	// A lower case only version of the page for searching
     	String lowerpage = fullpage.toLowerCase();

        // Text of one A tag
      	String tag;

    	// The A tags found so far
      	String links = "";

  		// Paste stuff on end of page to ensure searches succeed
      	fullpage = fullpage + " >";

 	 	tagPos = lowerpage.indexOf("<a href",0);

		while (tagPos >= 0 ) {
  	   		tagEnd = fullpage.indexOf(">",tagPos+1);
  	   		tag = fullpage.substring(tagPos, tagEnd+1);
  	   		links = links + tag + "\n";
  			tagPos = lowerpage.indexOf("<a href", tagEnd);
		}

		return links;
 	}


}



