from wxPython.wx import *
from wxPython.html import *

import urllib, sys

if sys.path[0] == "":
    snarfdir = "."
else:
    snarfdir = sys.path[0]

class panelbrowser(wxPanel):
    def __init__(self, frame, nb, sb):
        wxPanel.__init__(self, nb, -1)
        self.sb = sb # Statusbar
        #self.log = log
        #self.SetAutoLayout(true)
        #EVT_SCROLLWIN( self, self.OnScroll )
        self.html = MyHtmlWindow(self, sb)
        #win32
        self.html.SetRelatedFrame(frame, 'Snarfzilla 0.0.5  %s')
        self.html.SetRelatedStatusBar(0)

        self.box = wxBoxSizer(wxVERTICAL)
        self.box.Add(self.html, 1, wxGROW)

        subbox = wxBoxSizer(wxHORIZONTAL)

        btn = wxButton(self, 1202, "Load File")
        EVT_BUTTON(self, 1202, self.OnLoadFile)
        subbox.Add(btn, 1, wxGROW | wxALL, 2)

        btn = wxButton(self, 1204, "Back")
        EVT_BUTTON(self, 1204, self.OnBack)
        subbox.Add(btn, 1, wxGROW | wxALL, 2)

        btn = wxButton(self, 1205, "Forward")
        EVT_BUTTON(self, 1205, self.OnForward)
        subbox.Add(btn, 1, wxGROW | wxALL, 2)

        btn = wxButton(self, 1206, "View Source")
        EVT_BUTTON(self, 1206, self.OnViewSource)
        subbox.Add(btn, 1, wxGROW | wxALL, 2)

        self.box.Add(subbox, 0, wxGROW)
        self.SetSizer(self.box)
        self.SetAutoLayout(true)

        self.OnShowDefault(None)


    def OnShowDefault(self, event):
        #name = os.path.join(self.cwd, '/index.html')
        name = ('%s/htdocs/index.html' % snarfdir)
        self.html.LoadPage(name)


    def OnLoadFile(self, event):
        dlg = wxFileDialog(self, wildcard = '*.htm*', style=wxOPEN)
        if dlg.ShowModal():
            path = dlg.GetPath()
            self.html.LoadPage(path)
        dlg.Destroy()

    def OnBack(self, event):
        if not self.html.HistoryBack():
            wxMessageBox("No more items in history!")


    def OnForward(self, event):
        if not self.html.HistoryForward():
            wxMessageBox("No more items in history!")


    def OnViewSource(self, event):
        from wxPython.lib.dialogs import wxScrolledMessageDialog
        source = self.html.GetParser().GetSource()
        dlg = wxScrolledMessageDialog(self, source, 'HTML Source')
        dlg.ShowModal()
        dlg.Destroy()


class MyHtmlWindow(wxHtmlWindow):
    def __init__(self, parent, sb):
        self.sb = sb
        wxHtmlWindow.__init__(self, parent)
        EVT_SCROLLWIN( self, self.OnScroll )

    def OnScroll( self, event ):
        event.Skip()


    def OnLinkClicked(self, linkinfo):
        url = linkinfo.GetHref()
        #self.base_OnLinkClicked(linkinfo)


        #print ('Clicked: %s\n' % url)
        try:
            wxBeginBusyCursor()
            #self.sb.SetStatusText(("Loading %s" % url), 0)
            wxYield() # hmmm
            # if Debug:
            #print "loading url %s" % url
            f = urllib.urlopen(url)
            fileout = f.read()

            '''
            There is a bug in wxHtml where the img src tag doesn't
            work unless the tag has no spaces. (img src = ' does not work)
            '''
            fileout = string.replace(fileout, "href = ", "href=")
            fileout = string.replace(fileout, "href= ", "href=")
            fileout = string.replace(fileout, "href =", "href=")
            fileout = string.replace(fileout, 'img src= "', 'img src="')
            fileout = string.replace(fileout, 'img src = "', 'img src="')
            fileout = string.replace(fileout, 'img src ="', 'img src="')
            fileout = string.replace(fileout, 'img SRC="', 'img src="')
            fileout = string.replace(fileout, 'src="', 'src="%s' % url)
            urlcache = string.replace(url, "/", "X")
            urlcache = string.replace(urlcache, ":", "Y")
            urlcache = urlcache + ".html"
            #print urlcache
            try:
                output = open('%s/htdocs/cache/%s' % (snarfdir, urlcache), 'w')
            except:
                print "ERROR"
            output.write(fileout)
            output.close()
            lastout = open(('%s/htdocs/cache/last.url' % snarfdir), 'w')
            lastout.write(url)
            lastout.close()
            #print "loading page %s" % urlcache
            self.LoadPage(('%s/htdocs/cache/%s' % (snarfdir, urlcache)))
        except:
            #self.sb.SetStatusText(("Loading %s" % url), 0)
            wxBeginBusyCursor()
            wxYield() # Let GUI update before zoning out with urlopen
            #print "Making full URL..."
            inurl = open('%s/htdocs/cache/last.url' % snarfdir, 'r')
            lasturl = inurl.read()
            fullurl = lasturl + url
            #print fullurl
            f = urllib.urlopen(fullurl)
            fileout = f.read()
            fileout = string.replace(fileout, "href = ", "href=")
            fileout = string.replace(fileout, "href= ", "href=")
            fileout = string.replace(fileout, "href =", "href=")
            fileout = string.replace(fileout, "href=", "href=%s" % fullurl)
            fileout = string.replace(fileout, 'img src="', 'img src="%s' % fullurl)
            fileout = string.replace(fileout, 'img SRC="', 'img src="%s' % fullurl)
            urlcache = string.replace(url, "/", "X")
            urlcache = string.replace(urlcache, ":", "Y")
            urlcache = string.replace(urlcache, "@", "Z")
            urlcache = urlcache + ".html"
            #print urlcache
            output = open('%s/htdocs/cache/%s' % (snarfdir, urlcache), 'w')
            output.write(fileout)
            output.close()
            self.LoadPage('%s/htdocs/cache/%s' % (snarfdir, urlcache))
            wxEndBusyCursor()
        #self.sb.SetStatusText(url, 0)
        wxEndBusyCursor()
    def OnSetTitle(self, title):
        #self.log.add('OnSetTitle: %s\n' % title)
        self.base_OnSetTitle(title)
