# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, get_object_or_404
from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.conf.urls import url
from django.contrib import messages
from django.db.models.query import QuerySet

from coin.members.models import Member, CryptoKey, LdapUser, MembershipFee
from coin.members.membershipfee_filter import MembershipFeeFilter
from coin.members.forms import MemberChangeForm, MemberCreationForm
from coin.utils import delete_selected
import autocomplete_light


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


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


class MemberAdmin(UserAdmin):
    list_display = ('id', 'status', 'username', 'first_name', 'last_name',
                    'organization_name', 'email', 'end_date_of_membership')
    list_display_links = ('id', 'username', 'first_name', 'last_name')
    list_filter = ('status', MembershipFeeFilter)
    search_fields = ['username', 'first_name', 'last_name', 'email']
    ordering = ('last_name',)
    actions = [delete_selected, 'set_as_member', 'set_as_non_member',
               'bulk_send_welcome_email']

    form = MemberChangeForm
    add_form = MemberCreationForm

    fieldsets = (
        ('Adhérent', {'fields': (
            ('status', 'resign_date'),
            'type',
            ('first_name', 'last_name', 'organization_name'))}),
        ('Coordonnées', {'fields': (
            'email',
            ('home_phone_number', 'mobile_phone_number'),
            'address',
            ('postal_code', 'city', 'country'))}),
        ('Authentification', {'fields': (
            ('username', 'password'))}),
        ('Permissions', {'fields': (
            ('is_active', 'is_staff', 'is_superuser'))})
    )

    add_fieldsets = (
        ('Adhérent', {'fields': (
            'status',
            'type',
            ('first_name', 'last_name', 'organization_name'))}),
        ('Coordonnées', {'fields': (
            'email',
            ('home_phone_number', 'mobile_phone_number'),
            'address',
            ('postal_code', 'city', 'country'))}),
        ('Authentification', {'fields': (
            ('username', 'password'),)}),
        ('Permissions', {'fields': (
            ('is_active', 'is_staff', 'is_superuser', 'date_joined'))})
    )

    radio_fields = {"type": admin.HORIZONTAL}

    save_on_top = True

    inlines = [CryptoKeyInline, MembershipFeeInline]

    def get_readonly_fields(self, request, obj=None):
        if obj:
            # Remove help_text for readonly field (can't do that in the Form
            # django seems to user help_text from model for readonly fields)
            username_field = [
                f for f in obj._meta.fields if f.name == 'username']
            username_field[0].help_text = ''
            return ['username', ]
        else:
            return []

    def set_as_member(self, request, queryset):
        rows_updated = queryset.update(status='member')
        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='not_member')
        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"

    def get_urls(self):
        """Custom admin urls"""
        urls = super(MemberAdmin, self).get_urls()
        my_urls = [
            url(r'^send_welcome_email/(?P<id>\d+)$',
                self.admin_site.admin_view(self.send_welcome_email),
                name='send_welcome_email'),
        ]
        return my_urls + urls

    def send_welcome_email(self, request, id):
        """
        Vue appelée lorsque l'admin souhaite envoyer l'email de bienvenue à un 
        membre.
        """
        # TODO : Add better perm here
        if request.user.is_superuser:
            member = get_object_or_404(Member, pk=id)
            member.send_welcome_email()
            messages.success(request,
                             'Le courriel de bienvenue a été envoyé à %s' % member.email)
        else:
            messages.error(
                request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
                         'courriels de bienvenue.')

        return HttpResponseRedirect(request.META["HTTP_REFERER"])

    def bulk_send_welcome_email(self, request, queryset):
        """
        Action appelée lorsque l'admin souhaite envoyer un lot d'email de bienvenue 
        depuis une sélection de membre dans la vue liste de l'admin
        """
        for member in queryset.all():
            self.send_welcome_email(request, member.id)
        messages.success(request,
                         'Le courriel de bienvenue a été envoyé à %d membre(s).' % queryset.count())
    bulk_send_welcome_email.short_description = "Envoyer le courriel de bienvenue"


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

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