'assumes pythoncom wrapper for db_added
as of iTunes 9.2, iBooks 1.1, can\'t set artwork for PDF files via automation'

def _cover_to_thumb(self, path, metadata, db_added, lb_added, format):

    from PIL import Image as PILImage
    from calibre.utils.zipfile import ZipFile
    if self.verbose:
        logger().info(('    %s._cover_to_thumb()' % self.__class__.__name__))
    thumb = None
    if metadata.cover:
        if (format == 'epub'):
            '\n                                                                Pre-shrink    cover\n                                                                self.MAX_COVER_WIDTH,    self.MAX_COVER_HEIGHT\n                                                                '
            try:
                img = PILImage.open(metadata.cover)
                width = img.size[0]
                height = img.size[1]
                (scaled, nwidth, nheight) = fit_image(width, height, self.MAX_COVER_WIDTH, self.MAX_COVER_HEIGHT)
                if scaled:
                    if self.verbose:
                        logger().info(('            cover    scaled    from    %sx%s    to    %sx%s' % (width, height, nwidth, nheight)))
                    img = img.resize((nwidth, nheight), PILImage.ANTIALIAS)
                    cd = cStringIO.StringIO()
                    img.convert('RGB').save(cd, 'JPEG')
                    cover_data = cd.getvalue()
                    cd.close()
                else:
                    with lopen(metadata.cover, 'r+b') as cd:
                        cover_data = cd.read()
            except:
                self.problem_titles.append(("'%s'    by    %s" % (metadata.title, authors_to_string(metadata.authors))))
                logger().error(("        error    scaling    '%s'    for    '%s'" % (metadata.cover, metadata.title)))
                import traceback
                traceback.print_exc()
                return thumb
            if isosx:
                "\n                                                                                The    following    commands    generate    an    error,    but    the    artwork    does    in    fact\n                                                                                get    sent    to    the    device.        Seems    like    a    bug    in    Apple's    automation    interface?\n                                                                                Could    also    be    a    problem    with    the    integrity    of    the    cover    data?\n                                                                                "
                if lb_added:
                    delay = 2.0
                    attempts = 9
                    while attempts:
                        try:
                            lb_added.artworks[1].data_.set(cover_data)
                            break
                        except:
                            attempts -= 1
                            time.sleep(delay)
                            if self.verbose:
                                logger().info(('        waiting    %.1f    seconds    for    artwork    to    become    writable    (attempt    #%d)' % (delay, (10 - attempts))))
                    else:
                        if self.verbose:
                            logger().info('    failed    to    write    artwork')
                if db_added:
                    delay = 2.0
                    self._wait_for_writable_metadata(db_added, delay=delay)
                    attempts = 9
                    while attempts:
                        try:
                            db_added.artworks[1].data_.set(cover_data)
                            break
                        except:
                            attempts -= 1
                            time.sleep(delay)
                            if self.verbose:
                                logger().info(('        waiting    %.1f    seconds    for    artwork    to    become    writable    (attempt    #%d)' % (delay, (10 - attempts))))
                    else:
                        if self.verbose:
                            logger().info('    failed    to    write    artwork')
                    '\n                                                                                                try:\n                                                                                                                db_added.artworks[1].data_.set(cover_data)\n                                                                                                                logger().info("            writing    \'%s\'    cover    to    iDevice"    %    metadata.title)\n                                                                                                except:\n                                                                                                                if    self.verbose:\n                                                                                                                                logger().info("        iTunes    automation    interface    reported    an    error"\n                                                                                                                                                                                                    "    adding    artwork    to    \'%s\'    on    the    iDevice"    %    metadata.title)\n                                                                                                                #import    traceback\n                                                                                                                #traceback.print_exc()\n                                                                                                                #from    calibre    import    ipython\n                                                                                                                #ipython(user_ns=locals())\n                                                                                                                pass\n                                                                                                '
            elif iswindows:
                '    Write    the    data    to    a    real    file    for    Windows    iTunes    '
                tc = os.path.join(tempfile.gettempdir(), 'cover.jpg')
                with lopen(tc, 'wb') as tmp_cover:
                    tmp_cover.write(cover_data)
                if lb_added:
                    try:
                        if lb_added.Artwork.Count:
                            lb_added.Artwork.Item(1).SetArtworkFromFile(tc)
                        else:
                            lb_added.AddArtworkFromFile(tc)
                    except:
                        if self.verbose:
                            logger().info(("        iTunes    automation    interface    reported    an    error    when    adding    artwork    to    '%s'    in    the    iTunes    Library" % metadata.title))
                        pass
                if db_added:
                    delay = 2.0
                    self._wait_for_writable_metadata(db_added, delay=delay)
                    attempts = 9
                    while attempts:
                        try:
                            if db_added.Artwork.Count:
                                db_added.Artwork.Item(1).SetArtworkFromFile(tc)
                            else:
                                db_added.AddArtworkFromFile(tc)
                            break
                        except:
                            attempts -= 1
                            time.sleep(delay)
                            if self.verbose:
                                logger().info(('        waiting    %.1f    seconds    for    artwork    to    become    writable    (attempt    #%d)' % (delay, (10 - attempts))))
                    else:
                        if self.verbose:
                            logger().info('    failed    to    write    artwork')
        elif (format == 'pdf'):
            if self.verbose:
                logger().info('            unable    to    set    PDF    cover    via    automation    interface')
        try:
            width = metadata.thumbnail[0]
            height = metadata.thumbnail[1]
            im = PILImage.open(metadata.cover)
            im = im.resize((width, height), PILImage.ANTIALIAS)
            of = cStringIO.StringIO()
            im.convert('RGB').save(of, 'JPEG')
            thumb = of.getvalue()
            of.close()
            if self.verbose:
                logger().info(("            refreshing    cached    thumb    for    '%s'" % metadata.title))
            zfw = ZipFile(self.archive_path, mode='a')
            thumb_path = (path.rpartition('.')[0] + '.jpg')
            zfw.writestr(thumb_path, thumb)
        except:
            self.problem_titles.append(("'%s'    by    %s" % (metadata.title, authors_to_string(metadata.authors))))
            logger().error(("            error    converting    '%s'    to    thumb    for    '%s'" % (metadata.cover, metadata.title)))
        finally:
            try:
                zfw.close()
            except:
                pass
    elif self.verbose:
        logger().info(("            no    cover    defined    in    metadata    for    '%s'" % metadata.title))
    return thumb
