from django.contrib import admin
from django.utils import timezone

from .models import BaseModel, ModelLog, DataAccess

class SyncedObjectAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if isinstance(obj, BaseModel):
            obj.last_updated_by = request.user
            obj.last_update = timezone.now()
        super().save_model(request, obj, form, change)

    def delete_model(self, request, obj):
        obj.delete_dependencies() # object must implement delete_dependencies(self)
        obj.delete()

    def delete_queryset(self, request, queryset):
        for obj in queryset:
            obj.delete_dependencies() # object must implement delete_dependencies(self)
        queryset.delete()

class ModelLogAdmin(admin.ModelAdmin):
    list_display = ['user', 'formatted_time', 'operation', 'model_id', 'model_name', 'count']
    list_filter = ['user', 'operation', 'model_name']
    ordering = ['-date']
    search_fields = ['model_id']

class DataAccessAdmin(SyncedObjectAdmin):
    list_display = ['related_user', 'get_shared_users', 'model_name', 'model_id']
    list_filter = ['related_user', 'shared_with']
    ordering = ['-granted_at']

    @admin.display(description='Shared with')
    def get_shared_users(self, obj):
        return ", ".join([str(item) for item in obj.shared_with.all()])

# Register your models here.
admin.site.register(ModelLog, ModelLogAdmin)
admin.site.register(DataAccess, DataAccessAdmin)
