import csv

from django.contrib.auth.decorators import login_required, permission_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.text import slugify

from events.models import Event, Registration


@login_required
@permission_required("events.view_event", raise_exception=True)
def participants_csv(request, event_id):
    event = get_object_or_404(Event, id=event_id)

    # Create a CSV response
    filename = "{}-participants.csv".format(slugify(event.title))
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="{}"'.format(filename)
    writer = csv.writer(response)

    # The first line of the file is a header
    header = ["username", "email", "prénom", "nom de famille"]
    options_names = list(event.options.values_list("name", flat=True).order_by("id"))
    header += options_names
    extra_fields = list(
        event.extra_fields.values_list("name", flat=True).order_by("id")
    )
    header += extra_fields
    writer.writerow(header)

    # Next, one line by registered user
    registrations = Registration.objects.filter(event=event)
    for registration in registrations:
        user = registration.user
        row = [user.username, user.email, user.first_name, user.last_name]

        # Options
        all_choices = registration.options_choices.values_list("choice", flat=True)
        options_choices = [
            " & ".join(all_choices.filter(option__id=id).order_by("id"))
            for id in event.options.values_list("id", flat=True).order_by("id")
        ]
        row += options_choices
        # Extra info
        extra_info = list(
            registration.extra_info.values_list("content", flat=True).order_by(
                "field__id"
            )
        )
        row += extra_info

        writer.writerow(row)

    return response