'Retrieve and apply info from the autotagger for albums matched by
query and their items.'

def albums(self, lib, query, move, pretend, write):

    for a in lib.albums(query):
        album_formatted = format(a)
        if (not a.mb_albumid):
            self._log.info(u'Skipping    album    with    no    mb_albumid:    {0}', album_formatted)
            continue
        items = list(a.items())
        album_info = hooks.album_for_mbid(a.mb_albumid)
        if (not album_info):
            self._log.info(u'Release    ID    {0}    not    found    for    album    {1}', a.mb_albumid, album_formatted)
            continue
        track_index = defaultdict(list)
        for track_info in album_info.tracks:
            track_index[track_info.track_id].append(track_info)
        mapping = {}
        for item in items:
            candidates = track_index[item.mb_trackid]
            if (len(candidates) == 1):
                mapping[item] = candidates[0]
            else:
                for c in candidates:
                    if ((c.medium_index == item.track) and (c.medium == item.disc)):
                        mapping[item] = c
                        break
        self._log.debug(u'applying    changes    to    {}', album_formatted)
        with lib.transaction():
            autotag.apply_metadata(album_info, mapping)
            changed = False
            for item in items:
                item_changed = ui.show_model_changes(item)
                changed |= item_changed
                if item_changed:
                    apply_item_changes(lib, item, move, pretend, write)
            if (not changed):
                continue
            if (not pretend):
                for key in library.Album.item_keys:
                    a[key] = items[0][key]
                a.store()
                if (move and (lib.directory in util.ancestry(items[0].path))):
                    self._log.debug(u'moving    album    {0}', album_formatted)
                    a.move()
