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

"""
from django import forms
from django.urls import reverse, reverse_lazy
from django.utils.translation import gettext_lazy as _

from api.models import APIUserToken
from intervention.inputs import GenerateInput
from konova.forms import BaseForm
from user.models import User, UserNotification


class UserNotificationForm(BaseForm):
    """ Form for changing the notification settings of a user

    """
    notifications = forms.MultipleChoiceField(
        label_suffix="",
        label=_("Notifications"),
        required=False,  # allow total disabling of all notifications
        help_text=_("Select the situations when you want to receive a notification"),
        widget=forms.CheckboxSelectMultiple(
            attrs={
                "class": "list-unstyled",
            }
        ),
        choices=[]
    )

    def __init__(self, user: User, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        self.form_title = _("Edit notifications")
        self.form_caption = _("")
        self.action_url = reverse("user:notifications")
        self.cancel_redirect = reverse("user:index")

        # Insert all notifications into form field by creating choices as tuples
        notifications = UserNotification.objects.filter(
            is_active=True,
        )
        choices = []
        for n in notifications:
            choices.append(
                (n.id, _(n.name))
            )
        self.fields["notifications"].choices = choices

        users_current_notifications = self.user.notifications.all()
        users_current_notifications = [str(n.id) for n in users_current_notifications]
        self.fields["notifications"].initial = users_current_notifications

    def save(self):
        """ Stores the changes in the user konova_extension

        Returns:

        """
        selected_notification_ids = self.cleaned_data.get("notifications", [])
        notifications = UserNotification.objects.filter(
            id__in=selected_notification_ids,
        )
        self.user.notifications.set(notifications)


class UserAPITokenForm(BaseForm):
    token = forms.CharField(
        label=_("Token"),
        label_suffix="",
        max_length=255,
        required=True,
        help_text=_("Generated automatically - not editable"),
        widget=GenerateInput(
            attrs={
                "class": "form-control",
                "url": reverse_lazy("api:generate-new-token"),
            }
        )
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Create new token")
        self.form_caption = _("A new token needs to be validated by an administrator!")

        self.action_url = reverse("user:api-token")
        self.cancel_redirect = reverse("user:index")

        # Make direct token editing by user impossible. Instead set the proper url for generating a new token
        self.initialize_form_field("token", None)
        self.fields["token"].widget.attrs["readonly"] = True

    def save(self):
        """ Saves the form data

        Returns:
            api_token (APIUserToken)
        """
        user = self.instance
        new_token = self.cleaned_data["token"]
        if user.api_token is not None:
            user.api_token.delete()
        new_token = APIUserToken.objects.create(
            token=new_token
        )
        user.api_token = new_token
        user.save()
        return new_token