# Derived from Example in Chapter 9 of "Jython Essentials"
# by Samuele Pedroni, Noel Rappin.  March 2002 
# ISBN: 0-596-00247-5
# Copyright 2002 O'Reilly & Associates

import javax.swing as swing
import java
import string
from java.net import *
from java.io import *
from java.lang import StringBuffer
import time

ACTIVATED = swing.event.HyperlinkEvent.EventType.ACTIVATED
ENTERED = swing.event.HyperlinkEvent.EventType.ENTERED
EXITED = swing.event.HyperlinkEvent.EventType.EXITED

class HtmlBrowserWindow(swing.JFrame):
    

    def __init__(self, urlString="http://aqua.ssec.wisc.edu/db.html", callback=None):
    #def __init__(self, urlString="http://81.117.206.148/db.html", callback=None):
        swing.JFrame.__init__(self, title="Direct Broadcast Browser", size=(700, 400))
        self.contentPane.layout = java.awt.BorderLayout()
        self.htmlPane = swing.JEditorPane(urlString, editable=0,
                hyperlinkUpdate=self.followHyperlink, size=(400,600))
        self.contentPane.add(swing.JScrollPane(self.htmlPane),
                java.awt.BorderLayout.CENTER)
        self.status = swing.JLabel(" ", preferredSize=(400,20))
        self.contentPane.add(self.status, java.awt.BorderLayout.SOUTH)

        self.newURL = self.htmlPane.getPage()

        # added next for testing...may want to use WindowConstants.DISPOSE_ON_CLOSE
        self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE)
        self.callback = callback

    def followHyperlink(self, hlEvent):
        if hlEvent.eventType == ACTIVATED:
            sb = StringBuffer()

            if (((hlEvent.URL).toString()).lower().endswith(".hdf")) or (
               ((hlEvent.URL).toString()).lower().endswith(".nc")):
              #gotHDF(hlEvent.URL)
              self.callback(hlEvent.URL)
            else:
              self.htmlPane.setPage(hlEvent.URL)
              time.sleep(.3)
              self.newURL = self.htmlPane.getPage()

              dis = BufferedReader(InputStreamReader(self.newURL.openStream()))
              while 1:
                line = dis.readLine()
                if line == None: break

                #print line # just for testing

                # see if line is a link
                if line.find('HREF="t1.') > 0 or line.find('HREF="a1.') > 0 or line.find('HREF="AIRS.') > 0:
                  if line.find("1000m.hdf") > 0 or (line.find("AIRS_Rad") > 0 and line.find(".hdf") > 0):
                    sb.append(line+'\n')
                else:
                  sb.append(line+'\n')

              dis.close()
              self.htmlPane.setText(sb.toString())

        elif hlEvent.eventType == ENTERED:
            self.status.text = hlEvent.URL.toString()
        elif hlEvent.eventType == EXITED:
            self.status.text = " "
        
def gotHDF(url):
  # example to use a call-back to source...
  print "got HDF URL=",url
      
if __name__ == "__main__":
    HtmlBrowserWindow().show()
