'fill history_and_dataset_per_user.mako template with:
- user email
- the number of history and their size
- the number of dataset'

@web.expose
def history_and_dataset_per_user(self, trans, **kwd):

    message = escape(util.restore_text(kwd.get('message', '')))
    user_cutoff = int(kwd.get('user_cutoff', 60))
    sort_by = kwd.get('sorting', 'User')
    sorting = (0 if (sort_by == 'User') else (1 if (sort_by == 'HSort') else (2 if (sort_by == 'DSort') else 3)))
    descending = (1 if (kwd.get('descending', 'desc') == 'desc') else (-1))
    histories = sa.select((sa.func.count(galaxy.model.History.table.c.id).label('history'), galaxy.model.User.table.c.email.label('email')), from_obj=[sa.outerjoin(galaxy.model.History.table, galaxy.model.User.table)], whereclause=and_((galaxy.model.History.table.c.user_id == galaxy.model.User.table.c.id), (galaxy.model.History.table.c.deleted == 'f')), group_by=['email'], order_by=[sa.desc('email'), 'history'])
    datasets = sa.select((sa.func.count(galaxy.model.Dataset.table.c.id).label('dataset'), sa.func.sum(galaxy.model.Dataset.table.c.total_size).label('size'), galaxy.model.User.table.c.email.label('email')), from_obj=[galaxy.model.User.table, galaxy.model.Dataset.table, galaxy.model.HistoryDatasetAssociation.table, galaxy.model.History.table], whereclause=and_((galaxy.model.Dataset.table.c.id == galaxy.model.HistoryDatasetAssociation.table.c.dataset_id), (galaxy.model.History.table.c.id == galaxy.model.HistoryDatasetAssociation.table.c.history_id), (galaxy.model.History.table.c.user_id == galaxy.model.User.table.c.id), (galaxy.model.History.table.c.deleted == 'f')), group_by=['email'])
    histories = dict([((_.email if (_.email is not None) else 'Unknown'), int(_.history)) for _ in histories.execute()])
    datasets = dict([((_.email if (_.email is not None) else 'Unknown'), (int(_.dataset), int(_.size))) for _ in datasets.execute()])
    sorting_functions = [(lambda first, second: (descending if (first[0].lower() > second[0].lower()) else (- descending))), (lambda first, second: (descending if (histories.get(first, 0) < histories.get(second, 0)) else (- descending))), (lambda first, second: (descending if (datasets.get(first, [0])[0] < datasets.get(second, [0])[0]) else (- descending))), (lambda first, second: (descending if (datasets.get(first, [0, 0])[1] < datasets.get(second, [0, 0])[1]) else (- descending)))]
    users = list((set(histories.keys()) | set(datasets.keys())))
    users.sort(sorting_functions[sorting])
    if (user_cutoff > 0):
        users = users[:user_cutoff]
    data = collections.OrderedDict()
    for user in users:
        dataset = datasets.get(user, [0, 0])
        history = histories.get(user, 0)
        data[user] = (('%d    (%s)' % (history, int_to_octet(dataset[1]))), dataset[0])
    return trans.fill_template('/webapps/reports/history_and_dataset_per_user.mako', data=data, user_cutoff=user_cutoff, sorting=sorting, descending=descending, message=message)
