# vim:spell:spelllang=fr
# -*- encoding: utf-8 -*-

import csv

from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse

def export_as_csv(modeladmin, request, queryset):
    """
    Generic csv export admin action.
    """
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')
    writer = csv.writer(response)
    field_names = [field.name for field in opts.fields]
    m2m_field_names = [m2m_field.name for m2m_field in opts.many_to_many]
    # Write a first row with header information
    writer.writerow(field_names+m2m_field_names)
    # Write data rows
    for obj in queryset:
        values = [ unicode(getattr(obj, field)) for field in field_names]
        for m2m_field in m2m_field_names:
            value = getattr(obj, m2m_field)
            value = u','.join(map(unicode, value.all()))
            values.append(unicode(value))
        writer.writerow(map(lambda x: unicode.encode(x, 'utf8'), values))
    return response
export_as_csv.short_description = _(u"Exporter dans un fichier CSV")

def desactivate_user(modeladmin, request, queryset):
    queryset.update(is_active=False)
desactivate_user.short_description = _(u'Désactiver les utilisateurs sélectionnés')

def activate_user(modeladmin, request, queryset):
    queryset.update(is_active=True)
activate_user.short_description = _(u'Activer les utilisateurs sélectionnés')

