# Copyright (C) 2025 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later

from django.contrib import messages
from django.shortcuts import redirect
from django.utils.translation import gettext_lazy as _
from django.views.generic import CreateView, DetailView, UpdateView
from django_tables2 import SingleTableView

from tfjm.views import AdminMixin
from .forms import SurveyForm
from .models import Survey
from .tables import SurveyTable


class SurveyListView(AdminMixin, SingleTableView):
    model = Survey
    table_class = SurveyTable
    template_name = "survey/survey_list.html"


class SurveyCreateView(AdminMixin, CreateView):
    model = Survey
    form_class = SurveyForm


class SurveyDetailView(AdminMixin, DetailView):
    model = Survey


class SurveyInviteView(AdminMixin, DetailView):
    model = Survey

    def get(self, request, *args, **kwargs):
        survey = self.get_object()
        new_participants = survey.invite_all()
        if new_participants:
            messages.success(request, _("Invites sent!"))
        else:
            messages.warning(request, _("All invites were already sent."))
        return redirect("survey:survey_detail", survey.pk)


class SurveyRefreshCompletedView(AdminMixin, DetailView):
    model = Survey

    def get(self, request, *args, **kwargs):
        survey = self.get_object()
        survey.fetch_completion_data()
        messages.success(request, _("Completion data refreshed!"))
        return redirect("survey:survey_detail", survey.pk)


class SurveyUpdateView(AdminMixin, UpdateView):
    model = Survey
    form_class = SurveyForm
