"""
Author: Michel Peltriaux
Created on: 08.01.25

"""
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest
from django.shortcuts import render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.utils.translation import gettext_lazy as _

from konova.contexts import BaseContext
from konova.decorators import default_group_required
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from konova.utils.message_templates import NEW_API_TOKEN_GENERATED
from user.forms.modals.api_token import NewAPITokenModalForm


class APITokenView(View):

    @method_decorator(login_required)
    @method_decorator(default_group_required)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request: HttpRequest):
        template = "user/token.html"
        user = request.user

        context = {
            "user": user,
            TAB_TITLE_IDENTIFIER: _("User API token"),
        }
        context = BaseContext(request, context).context
        return render(request, template, context)


def new_api_token_view(request: HttpRequest):
    """ Function based view for processing ModalForm
    (Currently ModalForms only work properly with function based views)

    Args:
        request ():

    Returns:

    """
    user = request.user

    form = NewAPITokenModalForm(request.POST or None, instance=user, request=request)
    return form.process_request(
        request=request,
        msg_success=NEW_API_TOKEN_GENERATED,
        redirect_url=reverse("user:api-token"),
    )