#!/usr/bin/python

import wx, wx.py
import wx.lib.scrolledpanel as scrolledpanel
import urllib2, cStringIO, time, random

appopts = {}

class MainFrame(wx.Frame):
    pass

class ProgressPanelContainer(scrolledpanel.ScrolledPanel):
    def __init__(self, *args, **kwargs):
	scrolledpanel.ScrolledPanel.__init__(self, *args, **kwargs)
	self.sizer = wx.BoxSizer(wx.VERTICAL)
	self.SetSizer(self.sizer)
	self.SetAutoLayout(True)
	self.SetupScrolling()

class ProgressPanel(wx.Panel):
    def __init__(self, *args, **kwargs):
	wx.Panel.__init__(self, *args, **kwargs)

	# variables
	self.downloading = False
	self.sizer = wx.GridBagSizer(3, 6)
	self.SetSizer(self.sizer)
	self.SetAutoLayout(True)

	# progress bar
	self.progress = wx.Gauge(self)
	self.sizer.Add(self.progress, (0,0), (1,6), flag=wx.EXPAND)

	# download label
	self.download_label = wx.StaticText(self, label="Downloading:", style=wx.ALIGN_RIGHT)
	self.sizer.Add(self.download_label, (1,0), (1,2), flag=wx.EXPAND)

	# url area
	self.url_label = wx.StaticText(self, label="None")
	self.sizer.Add(self.url_label, (1,2), (1,2), flag= wx.EXPAND)

	# view image button
	self.view_image_btn = wx.Button(self, label="View &Image")
	self.view_image_btn.Disable()
	self.sizer.Add(self.view_image_btn, (2,0))

	# stop button
	self.stop_btn = wx.Button(self, label="&Stop")
	self.sizer.Add(self.stop_btn, (2,1))

	# X button
	self.x_btn = wx.Button(self, label="&Download Porn!")
	self.sizer.Add(self.x_btn, (2,2), flag=wx.EXPAND)

	# size label
	self.size_lbl = wx.StaticText(self, label="Size = 0")
	self.sizer.Add(self.size_lbl, (2,3), flag=wx.EXPAND)

	# set events
	self.stop_btn.Bind(wx.EVT_BUTTON, self.OnClickStop)
	self.x_btn.Bind(wx.EVT_BUTTON, self.OnClickX)

        # set growable row and column
        self.sizer.AddGrowableRow(0)
        self.sizer.AddGrowableCol(2)

    def OnClickStop(self, event):
	if self.stop_btn.GetLabel() == "Stop":
	    self.stop_btn.SetLabel("&Resume")
	else:
	    self.stop_btn.SetLabel("&Stop")

    def Slurp(self, *arg, **kwargs):
        """Slurp up the image in the background via Future Calls"""
	try:
	    if self.downloading:
		data = self.socket.read(4096)
		amount_read = len(data)
		if data:
		    self.data.write(data)
		    self.amount += amount_read
		    self.progress.SetValue(int((float(self.amount) / self.content_length) * 100))
		    self.future_call.Restart(10)
		else:
                    self.data.seek(0)
                    self._clean()
		    image = wx.ImageFromStream(self.data)
		    size = (image.GetWidth(), image.GetHeight())
		    bmp = wx.BitmapFromImage(image)
		    frame = wx.Frame(self, title="Yowza!", size=size)
		    wx.StaticBitmap(frame, bitmap=bmp)
		    frame.Show(True)
	except IOError, e:
            self._clean()
            self.Complain(e)

    def _clean(self):
        self.progress.SetValue(0)
        self.downloading = False
        self.amount = 0
        self.size_lbl.SetLabel("Size = 0")
        self.url_label.SetLabel("None")

    def Complain(self, message):
        dlg = wx.MessageDialog(self, style=wx.OK,
                               message="I can'a do it captin'!\n%s" % str(message),
                               caption="Trouble!")
        dlg.ShowModal()
        dlg.Destroy()

	
    def OnClickX(self, event):
	"""Starts a not-really-but-sort-of asynchronous network download"""
	if self.downloading: return
	else:
	    date = time.strftime("%y%m%d", (6,6,random.randint(1,30),1,1,1,1,1,1))
            url = 'http://playboy.com/sex/day/%s/imx/motd.jpg' % date
            self.url_label.SetLabel(url)
            try: self.socket = urllib2.urlopen(url)
            except IOError, e:
                self._clean()
                self.Complain(e)
                return
	    self.downloading = True
	    info = self.socket.info()
	    self.content_length = int(info['content-length'])
	    self.size_lbl.SetLabel("Size = %d" % self.content_length)
	    self.data = cStringIO.StringIO()
	    self.amount = 0
	    self.future_call = wx.FutureCall(20, self.Slurp, "test")


def main():
    app = wx.App()
    frame = wx.Frame(None, size=(729, 260),
                     title="Gallery Downloader")
    notebook = wx.Notebook(frame)

    shell = wx.py.shell.Shell(notebook, size=(700,100))
    notebook.AddPage(shell, "Interactive Prompt")
    
    progress = ProgressPanelContainer(notebook)
    notebook.AddPage(progress, "Progress")
    progress_panel1 = ProgressPanel(progress)
    progress.sizer.Add(progress_panel1, flag=wx.EXPAND)

    global appopts
    appopts['frame'] = frame
    appopts['progress1'] = progress_panel1
    frame.CenterOnScreen()
    frame.Show(True)
    shell.SetFocus()
    app.MainLoop()
    app.Exit()

if __name__ == '__main__':
    main()
