import mwclient.listing
import mwclient.page


class Image(mwclient.page.Page):

    def __init__(self, site, name, info=None):
        mwclient.page.Page.__init__(self, site, name, info,
                                    extra_properties={'imageinfo': (('iiprop', 'timestamp|user|comment|url|size|sha1|metadata|archivename'), )})
        self.imagerepository = self._info.get('imagerepository', '')
        self.imageinfo = self._info.get('imageinfo', ({}, ))[0]

    def imagehistory(self):
        return mwclient.listing.PageProperty(self, 'imageinfo', 'ii',
                                             iiprop='timestamp|user|comment|url|size|sha1|metadata|archivename')

    def imageusage(self, namespace=None, filterredir='all', redirect=False,
                   limit=None, generator=True):
        prefix = mwclient.listing.List.get_prefix('iu', generator)
        kwargs = dict(mwclient.listing.List.generate_kwargs(prefix, title=self.name, namespace=namespace, filterredir=filterredir))
        if redirect:
            kwargs['%sredirect' % prefix] = '1'
        return mwclient.listing.List.get_list(generator)(self.site, 'imageusage', 'iu', limit=limit, return_values='title', **kwargs)

    def duplicatefiles(self, limit=None):
        return mwclient.listing.PageProperty(self, 'duplicatefiles', 'df', dflimit=limit)

    def download(self):
        url = self.imageinfo['url']
        if not url.startswith('http://'):
            url = 'http://' + self.site.host + url
        url = urllib.parse.urlparse(url)
        # TODO: query string
        return self.site.connection.get(url[1], url[2])

    def __repr__(self):
        return "<Image object '%s' for %s>" % (self.name.encode('utf-8'), self.site)

@@ -1357,210 +1357,724 @@
 self
-):%0A        url = self.imageinfo%5B'url'%5D%0A        if not url.startswith('http://'):%0A            url = 'http://' + self.site.host + url%0A        url = urllib.parse.urlparse(url)%0A        # TODO: query string%0A
+, destination=None):%0A        %22%22%22%0A        Download the file. If %60destination%60 is given, the file will be written%0A        directly to the stream. Otherwise the file content will be stored in memory%0A        and returned (with the risk of running out of memory for large files).%0A%0A        Recommended usage:%0A%0A            %3E%3E%3E with open(filename, 'wb') as fd:%0A            ...     image.download(fd)%0A%0A        Args:%0A            destination (file object): Destination file%0A        %22%22%22%0A        url = self.imageinfo%5B'url'%5D%0A        if destination is not None:%0A            res = self.site.connection.get(url, stream=True)%0A            for chunk in res.iter_content(1024):%0A                destination.write(chunk)%0A        else:%0A    
     
@@ -2116,20 +2116,17 @@
 (url
-%5B1%5D, url%5B2%5D)
+).content
 %0A%0A  

Fix Image.download method