"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: ksp-servicestelle@sgdnord.rlp.de
Created on: 22.08.22

"""
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.views import View
from django.utils.translation import gettext_lazy as _

from intervention.forms.modals.share import ShareModalForm
from konova.utils.message_templates import DATA_SHARE_SET


class AbstractShareByTokenView(View):
    model = None
    redirect_url = None
    
    class Meta:
        abstract = True

    def get(self, request, id: str, token: str):

        """ Performs sharing of an intervention

        If token given in url is not valid, the user will be redirected to the dashboard

        Args:
            request (HttpRequest): The incoming request
            id (str): Object's id
            token (str): Access token for object

        Returns:

        """
        user = request.user
        obj = get_object_or_404(self.model, id=id)
        # Check tokens
        if obj.access_token == token:
            # Send different messages in case user has already been added to list of sharing users
            if obj.is_shared_with(user):
                messages.info(
                    request,
                    _("{} has already been shared with you").format(obj.identifier)
                )
            else:
                messages.success(
                    request,
                    _("{} has been shared with you").format(obj.identifier)
                )
                obj.share_with_user(user)
            return redirect(self.redirect_url, id=id)
        else:
            messages.error(
                request,
                _("Share link invalid"),
                extra_tags="danger",
            )
            return redirect("home")


class AbstractShareFormView(View):
    model = None
    
    class Meta:
        abstract = True
        
    def get(self, request, id: str):
        """ Renders sharing form 

        Args:
            request (HttpRequest): The incoming request
            id (str): Object's id

        Returns:

        """
        obj = get_object_or_404(self.model, id=id)
        form = ShareModalForm(request.POST or None, instance=obj, request=request)
        return form.process_request(
            request,
            msg_success=DATA_SHARE_SET
        )
    
    def post(self, request, id: str):
        return self.get(request, id)
