import gtk
import os
import urllib2

try:
    import gnomevfs
except ImportError:
    import gnome.vfs as gnomevfs
        

class Downloader(gtk.Dialog):

    def __init__(self, path):

        self.__is_cancelled = False
        

        gtk.Dialog.__init__(self, title = "", buttons = (gtk.STOCK_CANCEL,
                                                         gtk.RESPONSE_CANCEL))
        self.set_default_size(300, 100)
        self.connect("response", self.__on_cancel)
        
        vbox = self.vbox

        hbox = gtk.HBox(False, 12)
        hbox.set_border_width(12)
        vbox.pack_start(hbox, True, True)
        img = gtk.Image()
        img.set_from_file(os.path.join(path, "download.png"))
        hbox.pack_start(img, False, False)

        vbox = gtk.VBox()
        hbox.pack_end(vbox, True, True)

        lbl = gtk.Label("<b>" + _("Retrieving:") + "</b>")
        lbl.set_use_markup(True)
        align = gtk.Alignment(0.0, 0.0)
        align.add(lbl)
        vbox.add(align)
        
        self.__label = gtk.Label("")
        self.__label.set_use_markup(True)
        align = gtk.Alignment(0.0, 0.0)
        align.add(self.__label)
        vbox.add(align)
            
        self.__bar = gtk.ProgressBar()
        vbox.add(self.__bar)            


    def __on_cancel(self, src, response):

        self.__is_cancelled = True
        pass
            
            
    def download(self, url, dest):

        # Test whether we have a buggy version of gnome.vfs
        use_gnome_vfs = False
        import gnome
        if (gnome.gnome_python_version[1] > 6 or
            gnome.gnome_python_version[2] > 1):
            use_gnome_vfs = True
        
        name = url
        if (len(name) >= 60):
            name = name[:30] + "..." + name[-30:]
        gtk.timeout_add(0, self.__label.set_text, "%s" % (name))
        gtk.timeout_add(0, self.__bar.set_fraction, 0)
        gtk.timeout_add(0, self.__bar.set_text, "Contacting...")

        gtk.timeout_add(0, self.show_all)
        self.__is_cancelled = False

        dest_fd = open(dest, "w")
        if (use_gnome_vfs):
            src_fd = gnomevfs.open(url)
            total_size = src_fd.get_file_info().size
        else:
            src_fd = urllib2.urlopen(url)
            total_size = src_fd.info().get("Content-Length", 0)
        so_far = 0
        while (not self.__is_cancelled):
            if (use_gnome_vfs):
                try:
                    data = src_fd.read(4096)
                except gnomevfs.EOFError:
                    break
            else:
                data = src_fd.read(4096)
                if (not data):
                    break
            dest_fd.write(data)
            so_far += len(data)
            value = (100 * so_far / max(0.1, float(total_size)))
            gtk.timeout_add(0, self.__bar.set_fraction, value / 100.0)
            gtk.timeout_add(0, self.__bar.set_text, "%i%%" % (value))
        #end while

        src_fd.close()
        dest_fd.close()
        
        gtk.timeout_add(0, self.hide)
