from django.contrib import admin
from comm_op.models import comm_opMessage
from django.contrib.auth.models import User

# Register your models here.

@admin.register(comm_opMessage)
class MessageAdmin(admin.ModelAdmin):
    save_as = True
    always_show_username = True
    fieldsets = [
        (None, {'fields': ['sKey','sTitle','sDesc', 'bDone']}),
        ('Date information', {'fields': ['dtStart','dtEnd']}),
        ('Auteur', {'fields': ['Author']}),
    ]

    list_display = ('sKey', 'sTitle', 'dtStart', 'dtEnd', 'sAuthor', 'bDone')
    list_filter = ['bDone']
    search_fields = ['sKey', 'sTitle']

    def save_model(self, request, obj, form, change):
        obj.sAuthor = obj.Author.first_name + " " + obj.Author.last_name
        obj.sAuthor = obj.Author.first_name + " " + obj.Author.last_name
        obj.save()

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(MessageAdmin, self).formfield_for_foreignkey(                                                db_field, request, **kwargs)
        if db_field.remote_field.model == User:
            field.label_from_instance = self.get_user_label
        return field

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        field = super(MessageAdmin, self).formfield_for_manytomany(                                                db_field, request, **kwargs)
        if db_field.remote_field.model == User:
            field.label_from_instance = self.get_user_label
        return field

    def get_user_label(self, user):
        name = user.get_full_name()
        username = user.username
        if not self.always_show_username:
            return name or username
        return (name and name != username and '%s (%s)' % (name, username)                or username)
