from django.conf import settings
from django.contrib import admin
from django.shortcuts import redirect
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.views.decorators.cache import never_cache

from .models import InstalledService, Module, Platform, Project, Service


@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}


@admin.register(Platform)
class PlatformAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}


@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}


@admin.register(InstalledService)
class InstalledServiceAdmin(admin.ModelAdmin):
    pass


@admin.register(Module)
class ModuleAdmin(admin.ModelAdmin):
    pass


@never_cache
def login(request, *args, **kwargs):
    try:
        auth_login_url = reverse(settings.LOGIN_URL)
    except NoReverseMatch:
        return admin.site.orig_login(request, *args, **kwargs)
    auth_login_url += '?%s' % request.GET.urlencode()
    return redirect(auth_login_url)


@never_cache
def logout(request, *args, **kwargs):
    try:
        return redirect(reverse(settings.LOGOUT_URL))
    except NoReverseMatch:
        return admin.site.orig_logout(request, *args, **kwargs)


if admin.site.login != login:
    admin.site.orig_login = admin.site.login
    admin.site.login = login

if admin.site.logout != logout:
    admin.site.orig_logout = admin.site.logout
    admin.site.logout = logout
