from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from ..models.comment import Comment
from mptt.admin import MPTTModelAdmin


class CommentInline(GenericTabularInline):
    model = Comment
    extra = 0
    fields = ('user', 'content', 'is_public')
    readonly_fields = ('create_time', )


@admin.register(Comment)
class CommentAdmin(MPTTModelAdmin):
    list_display = ("id", 'truncated_content', 'user', 'content_type',
                    'object_link', 'create_time', 'is_public')
    list_filter = ('content_type', 'is_public', 'create_time')
    search_fields = ('content', 'user__username')
    # 可点击进入编辑页的字段
    list_display_links = ('truncated_content', )
    mptt_level_indent = 20

    def truncated_content(self, obj):
        return obj.content[:50] + "..." if len(
            obj.content) > 50 else obj.content

    truncated_content.short_description = "内容"

    def object_link(self, obj):
        target = obj.content_object
        if target:
            return f'<a href="{target.get_absolute_url()}">{str(target)}</a>'
        return "-"

    object_link.short_description = "关联对象"
    object_link.allow_tags = True
