from NEMO.mixins import ModelAdminRedirectMixin
from django.contrib import admin

from NEMO_billing.institution_agreements.models import InstitutionAgreement, InstitutionAgreementDocuments
from NEMO_billing.institution_agreements.views import export_institution_agreements


@admin.action(description="Export selected service agreements in CSV")
def institution_agreements_export_csv(modeladmin, request, queryset):
    return export_institution_agreements(queryset.all())


class InstitutionAgreementDocumentsInline(admin.TabularInline):
    model = InstitutionAgreementDocuments
    extra = 1


@admin.register(InstitutionAgreement)
class InstitutionAgreementAdmin(ModelAdminRedirectMixin, admin.ModelAdmin):
    list_display = [
        "agreement_id",
        "name",
        "institution",
        "start_date",
        "expiration_date",
        "owner",
        "point_of_contact_name",
        "point_of_contact_email",
    ]
    list_filter = [
        ("institution", admin.RelatedOnlyFieldListFilter),
        "start_date",
        "expiration_date",
        ("owner", admin.RelatedOnlyFieldListFilter),
    ]
    filter_horizontal = ["core_facilities"]
    inlines = [InstitutionAgreementDocumentsInline]
    actions = [institution_agreements_export_csv]
    date_hierarchy = "start_date"
