from birds.models import Bird, BirdingLocation
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views import generic
from scrobbles.models import EBirdCSVImport as BirdingCSVImport
from scrobbles.views import (
    ScrobbleableDetailView,
    ScrobbleableListView,
    JsonableResponseMixin,
)


class BirdingLocationListView(ScrobbleableListView):
    model = BirdingLocation


class BirdingLocationDetailView(ScrobbleableDetailView):
    model = BirdingLocation


class BirdListView(generic.ListView):
    model = Bird
    paginate_by = 200
    ordering = "common_name"


class BirdDetailView(generic.DetailView):
    model = Bird
    slug_field = "uuid"


class BirdingCSVImportCreateView(
    LoginRequiredMixin, JsonableResponseMixin, generic.CreateView
):
    model = BirdingCSVImport
    fields = ["csv_file"]
    template_name = "scrobbles/upload_form.html"
    success_url = reverse_lazy("vrobbler-home")

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.original_filename = (
            form.cleaned_data["csv_file"].name
        )
        self.object.save()
        self.object.process()
        return HttpResponseRedirect(self.request.META.get("HTTP_REFERER"))


class BirdingCSVImportDetailView(LoginRequiredMixin, generic.DetailView):
    model = BirdingCSVImport
    slug_field = "uuid"
    template_name = "scrobbles/import_detail.html"

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user)

    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        context_data["title"] = "eBird CSV Import"
        return context_data
