"""
Simple CAS views - bare minimum implementation.
"""

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from django.http import HttpResponse
from django.views import View
from furl import furl


class SimpleCASLoginView(View):
    """Simple CAS login view."""

    def get(self, request):
        ticket = request.GET.get("ticket")

        if ticket:
            # Coming back from CAS with ticket - validate it
            service_url = request.build_absolute_uri().split("?")[
                0
            ]  # Remove query params

            user = authenticate(request=request, ticket=ticket, service=service_url)

            if user:
                login(request, user)
                return redirect(settings.LOGIN_REDIRECT_URL)
            else:
                return HttpResponse("Authentication failed", status=401)

        else:
            service_url = furl(request.build_absolute_uri())
            service_url.scheme = "https" if settings.DEBUG else "http"
            service_url.set(args={})
            cas_login_url = furl(settings.CAS_SERVER_URL) / "login"
            cas_login_url.set(args={"service": service_url.url})
            return redirect(cas_login_url.url)


class SimpleCASLogoutView(View):
    """Simple CAS logout view."""

    def get(self, request):
        logout(request)

        # Redirect to CAS logout
        cas_logout_url = f"{settings.CAS_SERVER_URL.rstrip('/')}/logout"
        return redirect(cas_logout_url)
