# -*- coding: utf-8 -*-
from django.contrib import admin
from coin.members.models import Member, CryptoKey, LdapUser, MembershipFee
from django import forms
from coin.members.membershipfee_filter import MembershipFeeFilter
import autocomplete_light

# class LdapUserAdmin(admin.ModelAdmin):
#    exclude = ['dn']
#    list_display = ['uid','first_name', 'last_name']
#    search_fields = ['first_name', 'last_name']
    #TODO : Déplacer dans LdapUser model (pre_save ?)
    #def save_model(self, request, obj, form, change):


class CryptoKeyInline(admin.StackedInline):
    model = CryptoKey
    extra = 0


class MembershipFeeInline(admin.TabularInline):
    model = MembershipFee
    extra = 0
    fields = ('start_date', 'end_date', 'amount')


class MemberAdmin(admin.ModelAdmin):
    list_display = ('id', 'status', 'first_name', 'last_name',
                    'organization_name', 'email', 'end_date_of_membership')
    list_display_links = ('id', 'first_name', 'last_name')
    list_filter = ('status', MembershipFeeFilter)
    search_fields = ['first_name', 'last_name', 'email']
    actions = ['set_as_member', 'set_as_non_member']

    fields = (
                'status',
                'type',
                ('first_name', 'last_name', 'organization_name'),
                ('email', 'home_phone_number', 'mobile_phone_number'),
                'address',
                ('postal_code', 'city', 'country'),
                ('entry_date', 'resign_date'),
                'ldap_cn'
             )

    radio_fields = {"type": admin.HORIZONTAL}

    save_on_top = True

    inlines = [CryptoKeyInline, MembershipFeeInline]
    
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ['ldap_cn',]
        else:
            return []

    def set_as_member(self, request, queryset):
        rows_updated = queryset.update(status='adherent')
        self.message_user(
            request,
            '%d membre(s) définis comme adhérent(s).' % rows_updated)
    set_as_member.short_description = 'Définir comme adhérent'

    def set_as_non_member(self, request, queryset):
        rows_updated = queryset.update(status='non_adherent')
        self.message_user(
            request,
            '%d membre(s) définis comme non adhérent(s).' % rows_updated)
    set_as_non_member.short_description = "Définir comme non adhérent"


class MembershipFeeAdmin(admin.ModelAdmin):
    list_display = ('member', 'end_date', 'amount')
    form = autocomplete_light.modelform_factory(MembershipFee)

admin.site.register(Member, MemberAdmin)
admin.site.register(MembershipFee, MembershipFeeAdmin)
# admin.site.register(LdapUser, LdapUserAdmin)
