'Set email alerts for selected repositories.'

@web.expose
@web.require_login('set    email    alerts')
def set_email_alerts(self, trans, **kwd):

    caller = kwd['caller']
    user = trans.user
    if user:
        repository_ids = util.listify(kwd.get('id', ''))
        total_alerts_added = 0
        total_alerts_removed = 0
        flush_needed = False
        for repository_id in repository_ids:
            repository = repository_util.get_repository_in_tool_shed(trans.app, repository_id)
            if repository.email_alerts:
                email_alerts = json.loads(repository.email_alerts)
            else:
                email_alerts = []
            if (user.email in email_alerts):
                email_alerts.remove(user.email)
                repository.email_alerts = json.dumps(email_alerts)
                trans.sa_session.add(repository)
                flush_needed = True
                total_alerts_removed += 1
            else:
                email_alerts.append(user.email)
                repository.email_alerts = json.dumps(email_alerts)
                trans.sa_session.add(repository)
                flush_needed = True
                total_alerts_added += 1
        if flush_needed:
            trans.sa_session.flush()
        message = ('Total    alerts    added:    %d,    total    alerts    removed:    %d' % (total_alerts_added, total_alerts_removed))
        kwd['message'] = message
        kwd['status'] = 'done'
    del kwd['operation']
    return trans.response.send_redirect(web.url_for(controller='repository', action=caller, **kwd))
