
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from mptt.admin import MPTTModelAdmin
from cap.decorators import template_list_item

from categories.models import Category


class CategoryListFilter(admin.SimpleListFilter):
    title = _('Category')
    parameter_name = 'category'

    def lookups(self, request, model_admin):
        for category in Category.objects.root_nodes():
            yield category.pk, "*" + category.name
            for child in category.get_children():
                yield child.pk, mark_safe("—") + child.name

    def queryset(self, request, queryset):
        if not self.value():
            return queryset
        return queryset.filter(category_id=self.value())


@admin.register(Category)
class CategoryAdmin(MPTTModelAdmin):

    list_display = (
        'id', 'name', 'order', 'code', 'icon', 'product_count', 'get_preview'
    )

    list_editable = ('name', 'order')

    fields = (
        ('parent', 'code', ),
        'name',
        'title',
        ('logo', 'icon', ),
        'description',
    )

    search_fields = ('name', 'code')

    @template_list_item('admin/list_item_preview.html', _('Preview'))
    def get_preview(self, item):
        return {'file': item.logo}

    @admin.display(description=_('Product count'))
    def product_count(self, item):
        return item.products.count()
