from django.contrib import admin

from toolshed.models import (
    InventoryItem, ItemProperty, ItemTag, Property, Tag, Category, StorageLocation, WorkflowInstance,
)


class ItemTagInline(admin.TabularInline):
    model = ItemTag
    extra = 0
    autocomplete_fields = ('tag',)


class ItemPropertyInline(admin.TabularInline):
    model = ItemProperty
    extra = 0
    autocomplete_fields = ('property',)


class InventoryItemAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'category', 'availability_policy', 'owned_quantity', 'owner',
                     'owner_group', 'storage_location', 'get_tags', 'get_properties')
    search_fields = ('name', 'description', 'category__name', 'availability_policy', 'owner__username',
                      'owner_group__name', 'storage_location__name', 'tags__name', 'itemproperty__property__name')
    inlines = (ItemTagInline, ItemPropertyInline)

    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related('tags', 'itemproperty_set__property')

    @admin.display(description='Tags')
    def get_tags(self, obj):
        return ', '.join(tag.name for tag in obj.tags.all())

    @admin.display(description='Properties')
    def get_properties(self, obj):
        return ', '.join(f'{ip.property.name}={ip.value}' for ip in obj.itemproperty_set.all())


admin.site.register(InventoryItem, InventoryItemAdmin)


class PropertyAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'category', 'unit_symbol', 'base2_prefix', 'dimensions', 'origin')
    search_fields = ('name', 'description', 'category__name', 'unit_symbol', 'origin')


admin.site.register(Property, PropertyAdmin)


class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'category', 'origin')
    search_fields = ('name', 'description', 'category__name', 'origin')


admin.site.register(Tag, TagAdmin)


class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'parent', 'origin')
    search_fields = ('name', 'description', 'parent__name', 'origin')


admin.site.register(Category, CategoryAdmin)


class StorageLocationAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'category', 'parent', 'owner')
    search_fields = ('name', 'description', 'category__name', 'parent__name', 'owner__username')
    list_filter = ('category', 'owner')


admin.site.register(StorageLocation, StorageLocationAdmin)


class WorkflowInstanceAdmin(admin.ModelAdmin):
    list_display = ('slug', 'state', 'owner', 'created_at', 'updated_at')
    search_fields = ('slug', 'owner__username')
    list_filter = ('state', 'created_at', 'owner')
    readonly_fields = ('created_at', 'updated_at')


admin.site.register(WorkflowInstance, WorkflowInstanceAdmin)
