# authentic2 - versatile identity manager
# Copyright (C) 2010-2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django import forms
from django.contrib import admin
from django.utils.functional import curry

from authentic2.attributes_ng.engine import get_service_attributes
from authentic2.forms.widgets import DatalistTextInput

from . import app_settings, models


class OIDCClaimInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        data = dict(get_service_attributes(getattr(self.instance, 'client', None))).keys()
        widget = self.fields['value'].widget
        widget.data = data
        widget.name = 'list__oidcclaim-inline'
        widget.attrs.update({'list': 'list__oidcclaim-inline'})

    class Meta:
        model = models.OIDCClaim
        fields = ['name', 'value', 'scopes']
        widgets = {
            'value': DatalistTextInput,
        }


class OIDCClaimInlineAdmin(admin.TabularInline):

    model = models.OIDCClaim
    form = OIDCClaimInlineForm
    extra = 0

    def get_formset(self, request, obj=None, **kwargs):
        initial = []
        # formsets are only saved if formset.has_changed() is True, so only set initial
        # values on the GET (display of the creation form)
        if request.method == 'GET' and not obj:
            initial.extend(app_settings.DEFAULT_MAPPINGS)
            self.extra = 5
        formset = super().get_formset(request, obj=obj, **kwargs)
        formset.__init__ = curry(formset.__init__, initial=initial)
        return formset


class OIDCClientAdmin(admin.ModelAdmin):
    list_display = ['name', 'slug', 'client_id', 'ou', 'identifier_policy', 'created', 'modified']
    list_filter = ['ou', 'identifier_policy']
    date_hierarchy = 'modified'
    readonly_fields = ['created', 'modified']
    inlines = [OIDCClaimInlineAdmin]


class OIDCAuthorizationAdmin(admin.ModelAdmin):
    list_display = ['client', 'user', 'created', 'expired']
    search_fields = ['user__first_name', 'user__last_name', 'user__email', 'user__username']
    date_hierarchy = 'created'
    readonly_fields = ['created', 'expired']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.prefetch_related('client')
        return qs

    def get_search_results(self, request, queryset, search_term):
        from django.contrib.contenttypes.models import ContentType

        from authentic2.a2_rbac.models import OrganizationalUnit as OU

        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        clients = models.OIDCClient.objects.filter(name__contains=search_term).values_list('pk')
        ous = OU.objects.filter(name__contains=search_term).values_list('pk')
        queryset |= self.model.objects.filter(
            client_ct=ContentType.objects.get_for_model(models.OIDCClient), client_id=clients
        )
        queryset |= self.model.objects.filter(client_ct=ContentType.objects.get_for_model(OU), client_id=ous)
        return queryset, use_distinct


class OIDCCodeAdmin(admin.ModelAdmin):
    list_display = ['client', 'user', 'uuid', 'created', 'expired']
    list_filter = ['client']
    search_fields = ['user__first_name', 'user__last_name', 'user__email', 'user__username', 'client__name']
    date_hierarchy = 'created'
    readonly_fields = ['uuid', 'created', 'expired', 'user', 'uuid', 'client', 'state', 'nonce']


class OIDCAccessTokenAdmin(admin.ModelAdmin):
    list_display = ['client', 'user', 'uuid', 'created', 'expired']
    list_filter = ['client']
    search_fields = ['user__first_name', 'user__last_name', 'user__email', 'user__username', 'client__name']
    date_hierarchy = 'created'
    readonly_fields = ['uuid', 'created', 'expired']


admin.site.register(models.OIDCClient, OIDCClientAdmin)
admin.site.register(models.OIDCAuthorization, OIDCAuthorizationAdmin)
admin.site.register(models.OIDCCode, OIDCCodeAdmin)
admin.site.register(models.OIDCAccessToken, OIDCAccessTokenAdmin)
