from django.contrib import admin
from .models import Order, Product, OrderProduct,Customer, Store


@admin.register(Store)
class StoreAdmin(admin.ModelAdmin):
    list_display = ('name', 'address', 'telephone')


@admin.register(OrderProduct)
class OrderProductAdmin(admin.ModelAdmin):
    def get_order_id(self, obj):
        return obj.order.id

    def get_product_name(self, obj):
        return obj.product.name
    list_display = ('get_order_id', 'get_product_name', 'info')


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name',)


@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ('name', 'telephone', 'address')


class OrderInlines(admin.TabularInline):
    model = OrderProduct
    fk_name = "order"
    extra = 1


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    def get_products(self, obj):
        #return "\n".join(['{}:{} | '.format(p.name, p.amount) for p in obj.order_products.all()])
        return "\n".join([str(p) for p in obj.order_products.all()])

    def get_customer_name(self, obj):
        return obj.customer.name

    def get_customer_telephone(self, obj):
        return obj.customer.telephone

    get_customer_name.admin_order_field = 'customer_name'  # Allows column order sorting
    get_customer_name.short_description = 'Customer Name'  # Renames column head

    get_customer_telephone.admin_order_field = 'customer_telephone'  # Allows column order sorting
    get_customer_telephone.short_description = 'Customer Telephone'  # Renames column head

    list_display = ('id', 'get_customer_name', 'get_customer_telephone', 'order_date', 'delivery_date', 'store', 'get_products')
    inlines = (OrderInlines,)