from django.contrib import admin
from django_admin_listfilter_dropdown.filters import DropdownFilter

from .models import KbCategory, KbCategoryName, KbCategoryDescription
from .models import KbEntry, KbEntryAnswer, KbEntryQuestion


def custom_titled_filter(title, c=admin.FieldListFilter):
    class Wrapper(c):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.title = title
    return Wrapper


class KbCategoryNameInline(admin.TabularInline):
    model = KbCategoryName
    extra = 0
class KbCategoryDescriptionInline(admin.TabularInline):
    model = KbCategoryDescription
    extra = 0

class KbCategoryAdmin(admin.ModelAdmin):
    list_display = ('slug', 'name', 'entries')
    inlines = (KbCategoryNameInline, KbCategoryDescriptionInline)

    def entries(self, instance):
        return instance.entry_set.count()

class KbEntryQuestionInline(admin.TabularInline):
    model = KbEntryQuestion
    extra = 0
class KbEntryAnswerInline(admin.StackedInline):
    model = KbEntryAnswer
    extra = 0

class KbEntryAdmin(admin.ModelAdmin):
    list_display = ('category', 'title', 'question', 'score', 'internal')
    list_filter = ('category', 'internal')
    search_fields = ('category', 'title', 'question', 'answer')
    inlines = (KbEntryQuestionInline, KbEntryAnswerInline)

    def score(self, instance):
        return "%d (%d votes)" % (instance.get_score(), instance.get_vote_count())


admin.site.register(KbCategory, KbCategoryAdmin)
admin.site.register(KbEntry, KbEntryAdmin)
