import string
from django.shortcuts import resolve_url
from django import forms
from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils.html import format_html
import django_lcore
import lcoreapi

from lambdainst.models import VPNUser
from payments.admin import UserCouponInline, UserLedgerInline


def make_user_link(user):
    change_url = resolve_url('admin:auth_user_change', user.id)
    return format_html('<a href="{}">{}</a>', change_url, user.username)

class VPNUserInline(admin.StackedInline):
    model = VPNUser
    can_delete = False
    fk_name = 'user'

    fields = ('notes', 'expiration', 'last_expiry_notice', 'notify_expiration',
              'last_vpn_auth_fail_notice', 'notify_vpn_auth_fail',
              'trial_periods_given', 'referrer_a', 'campaign', 'last_vpn_auth', 'last_core_sync')
    readonly_fields = ('referrer_a', 'last_vpn_auth', 'last_core_sync', 'campaign')

    def referrer_a(self, object):
        if not object.referrer:
            return "-"

        s = make_user_link(object.referrer) + " "
        if object.referrer_used:
            s += _("(rewarded)")
        else:
            s += _("(not rewarded)")
        return s
    referrer_a.allow_tags = True
    referrer_a.short_description = _("Referrer")

    def is_paid(self, object):
        return object.is_paid
    is_paid.boolean = True
    is_paid.short_description = _("Is paid?")


class UserAdmin(UserAdmin):
    inlines = (VPNUserInline, UserLedgerInline, UserCouponInline)
    list_display = ('username', 'email', 'is_staff', 'date_joined', 'is_paid')
    ordering = ('-date_joined', )
    fieldsets = (
        (None, {'fields': ('username', 'password', 'email', 'links')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
    )
    readonly_fields = ('last_login', 'date_joined', 'links')
    actions = (django_lcore.core_sync_action, )

    def is_paid(self, object):
        return object.vpnuser.is_paid
    is_paid.boolean = True
    is_paid.short_description = _("Is paid?")

    def links(self, object):
        payments_url = resolve_url('admin:payments_payment_changelist')
        tickets_url = resolve_url('admin:tickets_ticket_changelist')
        fmt = '<a href="{}?user__id__exact={}">{}</a>'
        return format_html(fmt + " - " + fmt,
            payments_url, object.id, "Payments",
            tickets_url, object.id, "Tickets",
        )

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)

        # Notify core
        if change:
            django_lcore.sync_user(obj.vpnuser)

    def delete_model(self, request, obj):
        try:
            django_lcore.api.get_user(obj.username).delete()
        except lcoreapi.APIError as e:
            messages.error(request, "failed to delete vpn user: %r" % e)

        super().delete_model(request, obj)


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