from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _

from account import utils
from account.forms import ProfileForm, SchoolForm
from account.models import City, School, Tag, ProfileHighSchoolInfo, \
    ProfileCollegeInfo, ProfileTagVote, ContactRecord, Profile
    
from quanquan.admin import EditedTracableAdmin


# Define a new User admin
class UserAdmin(AuthUserAdmin):
    list_display = ('username', 'email', 'nickname', 'is_staff')
    readonly_fields = ['profile_link', ]
    
    def get_fieldsets(self, request, obj=None):
        # since lazy_translation is not easy to distinguished,
        # I will always assume that index=1 is what I am looking for
        result = super(UserAdmin, self).get_fieldsets(request, obj)
        # (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        if obj is None:
            return result
        target_section_fields = result[1][1]['fields']
        if 'profile_link' not in target_section_fields:
            result[1][1]['fields'] = target_section_fields + ('profile_link', )
            
        return result
        
    def nickname(self, instance):
        return self.profile_link(instance)
    nickname.allow_tags = True   
    nickname.short_description = _('nickname')
    
    def profile_link(self, instance=None):
        profile_id = instance._default_manager.filter(pk=instance.pk).values_list('profile__id', flat=True)[0]
        if profile_id :
            if instance.first_name:
                result = format_html('<a href="{0}">{1}</a>',
                               reverse('admin:account_profile_change', args=(profile_id,)),
                               instance.first_name)
            else:
                result = _('Please add first name for this user first!')
        else:
            result = format_html('<a href="{0}?user={1}">{2}</a>',
                           reverse('admin:account_profile_add'), instance.pk,
                           _('Create new profile for this user'))
        return result 
    profile_link.allow_tags = True
    profile_link.short_description = _('profile link')
    

@admin.register(City)
class CityAdmin(admin.ModelAdmin):
    list_display = ['name', 'abbr', 'state', 'longitude', 'latitude', ]
    search_fields = ['name', 'abbr', 'state', 'longitude', 'latitude', ]
    list_filter = ['state', ] 
    

@admin.register(School)
class SchoolAdmin(EditedTracableAdmin, admin.ModelAdmin):
    list_display = ['name', 'city', 'type', 'edited_by', 'last_edited', 'created_by', 'created_date', ]
    search_fields = ['name', 'city__name']
    list_filter = ['city__state', 'type', 'edited_by', 'created_by',] 
    fieldsets = (
        (None, {'fields': ('name', 'type', 'city', 'remark',)}),
    )
    
    form = SchoolForm

class ChildrenTagsInline(admin.TabularInline):
    model = Tag
    fields = ['name', ]

@admin.register(Tag)
class TagAdmin(EditedTracableAdmin, admin.ModelAdmin):
    list_display = ['name', 'parent', 'edited_by', 'last_edited', 'created_by', 'created_date', ]
    search_fields = ['name']
    list_filter = ['edited_by', 'created_by',] 
    date_hierarchy = 'last_edited'
    inlines = [ChildrenTagsInline, ]
    fieldsets = (
        (None, {'fields': ('name', 'parent')}),
    )

class ProfileHighSchoolInfoInline(admin.TabularInline):
    model = ProfileHighSchoolInfo
    fields = ['profile', 'school', 'date_joined', 'date_graduated', ]

class ProfileCollegeInfoInline(admin.TabularInline):
    model = ProfileCollegeInfo
    fields = ['profile', 'school', 'date_joined', 'date_graduated', ]

class ProfilesTagsInline(admin.TabularInline):
    model = ProfileTagVote
    fields = ['tag', 'count']

class ContactRecordInline(admin.TabularInline):
    model = ContactRecord
    fk_name = 'from_profile'

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'nickname_link', 'date_of_birth', 'reputation', ]
    search_fields = ['nickname']
    list_filter = ['reputation', ]
    readonly_fields = ['user_link', ]
    
    form = ProfileForm
    
    inlines = [ProfileHighSchoolInfoInline, ProfileCollegeInfoInline, ProfilesTagsInline, ContactRecordInline]
    
    def get_urls(self):
        from django.conf.urls import url

        urls = super(ProfileAdmin, self).get_urls()
        urls = [
            url(r'^bulk-create/$', self.admin_site.admin_view(self.bulk_creation), 
                name='%s_%s_bulk_create' % (self.model._meta.app_label, self.model._meta.model_name, ))
        # must be the latter one or 
        # url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info)will take over first
        ] + urls 
        return urls

    def get_fieldsets(self, request, obj=None):
        # since lazy_translation is not easy to distinguished,
        # I will always assume that index=1 is what I am looking for
        result = super(ProfileAdmin, self).get_fieldsets(request, obj)
        # (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        target_section_fields = result[0][1]['fields']
        if not isinstance(target_section_fields[0], (list, tuple)):
            result[0][1]['fields'][0] = (target_section_fields[0], 'user_link', )
        # we found a dulplicated user_link, and don't know why yet
        # below as short term solution
        result[0][1]['fields'] = [x for x in result[0][1]['fields'] if x != 'user_link']
        return result
    
    def bulk_creation(self, request):

        f = request.FILES.get('creation_file')
        if not f:
            self.message_user(request, 'no file selected', messages.WARNING)
            return redirect(reverse('admin:%s_%s_changelist' % (self.model._meta.app_label, 
                                                                           self.model._meta.model_name,)))
        try: 
            row_counter = utils.bulk_create(f)
        except Exception as e:
            self.message_user(request, 'row: %d, error: %s' %(e.row_counter, e), messages.ERROR)
        else:
            self.message_user(request, "Successfully created %d profiles." % row_counter)

        return redirect(reverse('admin:account_profile_changelist'))
    bulk_creation.short_description = _('Batch creation from excel')
    
    def nickname_link(self, instance):
        user_id = instance._default_manager.filter(pk=instance.pk).values_list('user__id', flat=True)[0]
        if user_id :
            result = format_html('{0}<a href="{1}">{2}</a>',
                                 instance.nickname if instance.nickname else 'unknown',
                               reverse('admin:auth_user_change', args=(user_id,)),
                               _('Edit basic info'))
        else:
            result = _('An associated user required')
        return result
    nickname_link.allow_tags = True   
    nickname_link.short_description = _('nickname')
        
    def user_link(self, instance):
        if instance.pk is None:
            user_id = None
        else:
            user_id = instance._default_manager.filter(pk=instance.pk).values_list('user__id', flat=True)[0]
        if user_id :
            result = format_html('<a href="{0}">{1}</a>',
                               reverse('admin:auth_user_change', args=(user_id,)),
                               _('Go'))
        else:
            result = _('An associated user required')
        return result
    user_link.allow_tags = True   
    user_link.short_description = _('edit basic info')


# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)