import csv

from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.utils.encoding import force_str
from django.utils.translation import gettext as _


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(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % force_str(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 = [force_str(getattr(obj, field)) for field in field_names]
        for m2m_field in m2m_field_names:
            value = getattr(obj, m2m_field)
            value = ','.join(map(force_str, value.all()))
            values.append(force_str(value))
        writer.writerow(map(lambda x: force_str(x), values))
    return response


export_as_csv.short_description = _('Export selected objects as csv file')


def activate_selected(modeladmin, request, queryset):
    queryset.update(is_active=True)


activate_selected.short_description = _('Activate selected objects')


def deactivate_selected(modeladmin, request, queryset):
    queryset.update(is_active=False)


deactivate_selected.short_description = _('De-activate selected objects')
