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

"""
from dal import autocomplete
from django import forms
from django.utils.translation import gettext_lazy as _

from intervention.inputs import TextToClipboardInput
from konova.forms.modals import BaseModalForm
from konova.utils.message_templates import ENTRY_REMOVE_MISSING_PERMISSION
from konova.utils.user_checks import is_default_group_only
from user.models import Team, User


class ShareModalForm(BaseModalForm):
    url = forms.CharField(
        label=_("Share link"),
        label_suffix="",
        help_text=_("Send this link to users who you want to have writing access on the data"),
        required=False,
        widget=TextToClipboardInput(
            attrs={
                "readonly": True,
                "class": "form-control",
            }
        )
    )
    teams = forms.ModelMultipleChoiceField(
        label=_("Add team to share with"),
        label_suffix="",
        help_text=_("Multiple selection possible - You can only select teams which do not already have access."),
        required=False,
        queryset=Team.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(
            url="user:share-team-autocomplete",
            attrs={
                "data-placeholder": _("Click for selection"),
                "data-minimum-input-length": 3,
            },
        ),
    )
    users = forms.ModelMultipleChoiceField(
        label=_("Add user to share with"),
        label_suffix="",
        help_text=_("Multiple selection possible - You can only select users which do not already have access. Enter the full username."),
        required=False,
        queryset=User.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(
            url="user:share-user-autocomplete",
            attrs={
                "data-placeholder": _("Click for selection"),
                "data-minimum-input-length": 3,
            },
        ),
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Share")
        self.form_caption = _("Share settings for {}").format(self.instance.identifier)
        self.template = "modal/modal_form.html"

        # Make sure an access_token is set
        if self.instance.access_token is None:
            self.instance.generate_access_token()

        self._init_fields()

    def _user_team_valid(self):
        """ Checks whether users and teams have been removed by the user and if the user is allowed to do so or not

        Returns:

        """
        users = self.cleaned_data.get("users", User.objects.none())
        teams = self.cleaned_data.get("teams", Team.objects.none())

        _is_valid = True
        if is_default_group_only(self.user):
            shared_users = self.instance.shared_users
            shared_teams = self.instance.shared_teams

            shared_users_are_removed = not set(shared_users).issubset(users)
            shared_teams_are_removed = not set(shared_teams).issubset(teams)

            if shared_users_are_removed:
                self.add_error(
                    "users",
                    ENTRY_REMOVE_MISSING_PERMISSION
                )
                _is_valid = False
            if shared_teams_are_removed:
                self.add_error(
                    "teams",
                    ENTRY_REMOVE_MISSING_PERMISSION
                )
                _is_valid = False
        return _is_valid

    def is_valid(self):
        """ Extended validity check

        Returns:

        """
        super_valid = super().is_valid()
        user_team_valid = self._user_team_valid()
        _is_valid = super_valid and user_team_valid
        return _is_valid

    def _init_fields(self):
        """ Wraps initializing of fields

        Returns:

        """
        # Initialize share_link field
        share_link = self.instance.get_share_link()
        self.share_link = self.request.build_absolute_uri(share_link)
        self.initialize_form_field(
            "url",
            self.share_link
        )

        form_data = {
            "teams": self.instance.teams.all(),
            "users": self.instance.users.all(),
        }
        self.load_initial_data(form_data)

    def save(self):
        self.instance.update_shared_access(self)
