from copy import deepcopy #@UnresolvedImport
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group, User
from django.utils.translation import ugettext as _
from forms import LdtForm
from guardian.admin import GuardedModelAdmin
from models import Ldt, UserProfile, GroupProfile
from tastypie.admin import ApiKeyInline
from tastypie.models import ApiAccess, ApiKey


class GroupProfileInline(admin.StackedInline):
    model = GroupProfile

class GroupAdmin(GuardedModelAdmin):
    inlines = [GroupProfileInline, ]

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    
class UserProfileAdmin(UserAdmin):
    def add_view(self, *args, **kwargs):
        self.inlines = []
        return super(UserProfileAdmin, self).add_view(*args, **kwargs)
    
    def change_view(self, *args, **kwargs):
        self.inlines = [UserProfileInline]
        return super(UserAdmin, self).change_view(*args, **kwargs)


class LdtAdmin(UserProfileAdmin):    
    list_display = ('username', 'email', 'first_name', 'last_name')
    
    fieldsets = [
        (None, {'fields': ('username', ('password1', 'password2'))}),
        (_('User details'), {'fields': (('first_name', 'last_name'), 'email')}),
        (_('Groups'), {'fields': ('groups',)}),
        (_('Permissions'), {'fields': ('is_staff', 'user_permissions')}),
    ]    
    form = LdtForm
    model = Ldt
    filter_horizontal = ('user_permissions',)
    inlines = [UserProfileInline, ApiKeyInline]
    
    def get_fieldsets(self, request, obj=None): 
        fieldsets = deepcopy(self.fieldsets)
        if not '/add' in request.path:
            fieldsets[0] = (None, {'fields': ('username',)})
            fieldsets.append((_('Password'), {'fields': ('password1', 'password2'), 'classes': ('collapse',)}))
        return fieldsets
        
    def add_view(self, request):
        return super(UserAdmin, self).add_view(request)  
    
    

admin.site.unregister(Group)
admin.site.register(Group, GroupAdmin)

admin.site.unregister(Ldt) 
admin.site.register(Ldt, LdtAdmin)

admin.site.register(ApiKey)
admin.site.register(ApiAccess)

admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
