from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.utils.functional import cached_property
from django.views.generic import TemplateView

from servala.core.models import User
from servala.frontend.forms.profile import UserProfileForm
from servala.frontend.views.mixins import HtmxUpdateView


class IndexView(TemplateView):
    template_name = "frontend/index.html"


class OrganizationSelectionView(LoginRequiredMixin, TemplateView):
    template_name = "frontend/organization_selection.html"

    @cached_property
    def user_organizations(self):
        return self.request.user.organizations.all()

    def dispatch(self, request, *args, **kwargs):
        # Users with a single organization get redirected to the organization’s dashboard
        if self.user_organizations.count() == 1:
            organization = self.user_organizations.first()
            return redirect(organization.urls.base)
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["user_organizations"] = self.user_organizations.annotate(
            instance_count=Count("service_instances")
        )
        return context


class ProfileView(HtmxUpdateView):
    template_name = "frontend/profile.html"
    form_class = UserProfileForm
    success_url = reverse_lazy("frontend:profile")
    fragments = ("user-email", "user-email-edit", "user-company", "user-company-edit")
    model = User

    def has_permission(self):
        return True

    def get_object(self):
        return self.request.user

    @cached_property
    def object(self):
        return self.get_object()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        keycloak_settings = settings.SOCIALACCOUNT_PROVIDERS["openid_connect"]
        keycloak_server_url = keycloak_settings["APPS"][0]["settings"]["server_url"]
        account_url = keycloak_server_url.replace(
            "/.well-known/openid-configuration", "/account"
        )
        context["account_href"] = account_url
        return context

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)


def custom_404(request, exception):
    return render(request, "404.html", status=404)


def custom_403(request, exception):
    return render(request, "403.html", status=403)


def custom_500(request):
    return render(request, "500.html", status=500)
