'Returns autocomplete data for tag names ordered from most frequently used to
least frequently used.'

def _get_tag_autocomplete_names(self, trans, q, limit, timestamp, user=None, item=None, item_class=None):

    if ((item is None) and (item_class is None)):
        raise RuntimeError('Both    item    and    item_class    cannot    be    None')
    elif (item is not None):
        item_class = item.__class__
    item_tag_assoc_class = self.get_tag_handler(trans).get_tag_assoc_class(item_class)
    cols_to_select = [item_tag_assoc_class.table.c.tag_id, func.count('*')]
    from_obj = item_tag_assoc_class.table.join(item_class.table).join(trans.app.model.Tag.table)
    where_clause = and_(trans.app.model.Tag.table.c.name.like((q + '%')), (item_tag_assoc_class.table.c.user_id == user.id))
    order_by = [func.count('*').desc()]
    group_by = item_tag_assoc_class.table.c.tag_id
    query = select(columns=cols_to_select, from_obj=from_obj, whereclause=where_clause, group_by=group_by, order_by=order_by, limit=limit)
    result_set = trans.sa_session.execute(query)
    ac_data = '#Header|Your    Tags\n'
    for row in result_set:
        tag = self.get_tag_handler(trans).get_tag_by_id(row[0])
        if ((item is not None) and self.get_tag_handler(trans).item_has_tag(trans.user, item, tag)):
            continue
        tag_names = self._get_usernames_for_tag(trans, trans.user, tag, item_class, item_tag_assoc_class)
        ac_data += (((tag_names[0] + '|') + tag_names[0]) + '\n')
    return ac_data
