from django.contrib import admin
from django.db.models import Count, Q

from . import models


class PublicProfessionalSphereAdmin(admin.ModelAdmin):

    search_fields = (
        'name_ru',
        'name_en',
    )

    list_display = (
        'id',
        'name_ru',
        'name_en',
        'position',
        'slug',
        'public_professions_count',
    )

    list_editable = (
        'name_ru',
        'name_en',
        'position',
        'slug',
    )

    readonly_fields = ('public_professions_count',)

    def public_professions_count(self, obj):
        return obj.public_professions_count

    def get_queryset(self, request):
        return (
            super().get_queryset(request)
            .annotate(
                public_professions_count=Count(
                    expression='public_professions',
                    filter=Q(public_professions__is_active=True),
                ),
            )
        )


class PublicProfessionAdmin(admin.ModelAdmin):

    search_fields = (
        'name_ru',
        'name_en',
        'slug',
    )

    list_display = (
        'id',
        'slug',
        'name_ru',
        'name_en',
        'public_professional_sphere',
        'position',
        'is_active',
    )

    list_filter = (
        'is_active',
    )

    list_editable = (
        'position',
        'is_active',
        'slug',
    )

    filter_horizontal = (
        'professions',
    )

    ordering = (
        'name_ru',
    )


admin.site.register(models.PublicProfessionalSphere, PublicProfessionalSphereAdmin)
admin.site.register(models.PublicProfession, PublicProfessionAdmin)
