from django_object_actions import DjangoObjectActions, takes_instance_or_queryset

from django.contrib import admin, messages
from django.utils.translation import gettext_lazy as _

from .models import EnrolledUsersReport, ReportFile
from .tasks import run_report_task


class ReportReRunActionMixin(DjangoObjectActions):
    actions = [
        'rerun_action',
    ]

    change_actions = [
        'rerun_action',
    ]

    def rerun_action_base(self, request):
        self.message_user(
            request=request,
            message=_('перегенерация отчетов запущена'),
            level=messages.INFO,
        )

    @takes_instance_or_queryset
    def rerun_action(self, request, queryset):
        for report in queryset:
            run_report_task.delay(report_id=report.id, force=True)

        return self.message_user(
            request=request,
            message=_('перегенерация отчетов запущена'),
            level=messages.INFO,
        )

    rerun_action.label = _("перегенерировать отчет")
    rerun_action.short_description = _("перегенерировать отчеты")


@admin.register(ReportFile)
class ReportFileAdmin(ReportReRunActionMixin, admin.ModelAdmin):
    list_display = ('id', 'status', 'report_type', 'created', 'modified')
    list_filter = (
        'report_type',
    )
    readonly_fields = (
        'id',
        'report_type',
    )
    fields = (
        'status',
        'error_message',
        'file',
    ) + readonly_fields


class BaseReportFileAdmin(ReportReRunActionMixin, admin.ModelAdmin):
    list_display = ('id', 'status', 'created', 'modified')
    readonly_fields = (
        'id',
    )
    fields = (
        'status',
        'error_message',
        'file',
    ) + readonly_fields


@admin.register(EnrolledUsersReport)
class EnrolledUsersReportAdmin(BaseReportFileAdmin):
    list_display = BaseReportFileAdmin.list_display + ('course',)
    fields = BaseReportFileAdmin.fields + ('course',)
    raw_id_fields = ('course',)
