# coding: utf-8

from django import forms
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.utils.translation import ugettext_lazy as _
from shop import app_settings
from shop.models import (
    OrderModel,
    OrderItemModel,
    OrderExtraInfo,
    ExtraOrderPriceField,
    OrderPayment,
    AddressModel,
    Country)


class LocalizeDecimalFieldsForm(forms.ModelForm):
    """Localize Decimal field names."""

    def __new__(cls, *args, **kwargs):
        new_class = super(LocalizeDecimalFieldsForm, cls).__new__(cls)
        if hasattr(new_class, 'base_fields'):
            for field in list(new_class.base_fields.values()):
                if isinstance(field, (forms.DecimalField, forms.FloatField)):
                    field.localize = True
                    field.widget.is_localized = True
        return new_class


class LocalizeDecimalFieldsMixin(object):
    """Localize input fields for models of type DecimalField in the admin interface.

    To be used as a mixin for classes derived from admin.ModelAdmin, admin.TabularInline ...
    If your class derived from ModelAdmin wants to override the form attribute,
    make sure that this form is derived from LocalizeDecimalFieldsForm and not
    from forms.ModelForm.
    """
    form = LocalizeDecimalFieldsForm


class OrderExtraInfoInline(admin.TabularInline):
    model = OrderExtraInfo
    extra = 0


class OrderPaymentInline(LocalizeDecimalFieldsMixin, admin.TabularInline):
    model = OrderPayment
    extra = 0


class ExtraOrderPriceFieldInline(LocalizeDecimalFieldsMixin, admin.TabularInline):
    model = ExtraOrderPriceField
    extra = 0


class OrderItemInline(LocalizeDecimalFieldsMixin, admin.TabularInline):
    model = OrderItemModel
    extra = 0
    raw_id_fields = ('product',)

# TODO: add ExtraOrderItemPriceField inline, ideas?


class OrderAdmin(LocalizeDecimalFieldsMixin, ModelAdmin):
    list_display = ('id', 'user', 'status', 'order_total', 'created')
    list_filter = ('status', 'user')
    search_fields = ('id', 'shipping_address_text', 'user__username')
    date_hierarchy = 'created'
    inlines = (
        OrderItemInline,
        OrderExtraInfoInline,
        ExtraOrderPriceFieldInline,
        OrderPaymentInline
    )
    readonly_fields = ('created', 'modified',)
    raw_id_fields = ('user',)
    fieldsets = (
        (None, {
            'fields': ('user', 'status', 'order_total',
                       'order_subtotal', 'created', 'modified')}),
        (_('Shipping'), {
            'fields': ('shipping_address_text',), }),
        (_('Billing'), {
            'fields': ('billing_address_text',) }),
    )

    def save_model(self, request, order, form, change):
        super(OrderAdmin, self).save_model(request, order, form, change)
        if not order.is_completed() and order.is_fully_paid():
            order.mark_as_paid()


class AddressAdmin(ModelAdmin):
    list_display = (
        'name', 'address', 'address2', 'zip_code', 'city', 'country',
        'user_shipping', 'user_billing')
    raw_id_fields = ('user_shipping', 'user_billing')


if app_settings.ORDER_MODEL.startswith("shop"):
    admin.site.register(OrderModel, OrderAdmin)

if app_settings.ADDRESS_MODEL.startswith("shop"):
    admin.site.register(AddressModel, AddressAdmin)
    admin.site.register(Country, ModelAdmin)
