from django.contrib import admin
from django.contrib.admin.apps import AdminConfig


class ReadOnlyAdmin(admin.ModelAdmin):
    """Generic read-only admin for system tables."""

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False


def _safe_register(model, model_admin):
    try:
        admin.site.register(model, model_admin)
    except admin.sites.AlreadyRegistered:
        pass


class Igny8AdminConfig(AdminConfig):
    default_site = 'igny8_core.admin.site.Igny8AdminSite'
    name = 'django.contrib.admin'

    def ready(self):
        super().ready()
        # Register Django internals in admin (read-only where appropriate)
        from django.contrib.admin.models import LogEntry
        from django.contrib.auth.models import Group, Permission
        from django.contrib.contenttypes.models import ContentType
        from django.contrib.sessions.models import Session

        _safe_register(LogEntry, ReadOnlyAdmin)
        _safe_register(Permission, admin.ModelAdmin)
        _safe_register(Group, admin.ModelAdmin)
        _safe_register(ContentType, ReadOnlyAdmin)
        _safe_register(Session, ReadOnlyAdmin)


