# barbacompta - invoicing for dummies
# Copyright (C) 2019-2020 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/>.

import taggit.admin
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.models import Group
from django.http import HttpResponseRedirect
from django.utils.http import urlencode
from django.views.decorators.cache import never_cache

User = get_user_model()


class EOGestionAdminSite(admin.AdminSite):
    @never_cache
    def login(self, request, extra_context=None):
        if "mellon" in settings.INSTALLED_APPS:
            next_url = request.GET.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL or "/")
            query = urlencode({REDIRECT_FIELD_NAME: next_url})
            url = f"/accounts/mellon/login/?{query}"
            return HttpResponseRedirect(url)
        return super().login(request, extra_context=extra_context)

    @never_cache
    def logout(self, request, extra_context=None):
        if "mellon" in settings.INSTALLED_APPS:
            next_url = request.GET.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL or "/")
            query = urlencode({REDIRECT_FIELD_NAME: next_url})
            url = f"/accounts/mellon/logout/?{query}"
            return HttpResponseRedirect(url)
        return super().logout(request, extra_context=extra_context)


site = EOGestionAdminSite()
site.register(User, UserAdmin)
site.register(Group, GroupAdmin)
site.register(taggit.admin.Tag, taggit.admin.TagAdmin)
