from django.conf import settings
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 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)
