"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 20.10.21

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

from codelist.models import KonovaCode
from codelist.settings import CODELIST_CONSERVATION_OFFICE_ID
from konova.forms import BaseForm


class TimespanReportForm(BaseForm):
    """ TimespanReporForm is used for allowing simple creation of an e.g. annual report for conservation offices

    """
    date_from = forms.DateField(
        label_suffix="",
        label=_("From"),
        help_text=_("Entries created from..."),
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
                "class": "form-control",
            },
            format="%d.%m.%Y"
        )
    )
    date_to = forms.DateField(
        label_suffix="",
        label=_("To"),
        help_text=_("Entries created until..."),
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
                "class": "form-control",
            },
            format="%d.%m.%Y"
        )
    )
    conservation_office = forms.ModelChoiceField(
        label=_("Conservation office"),
        label_suffix="",
        help_text=_("Select the responsible office"),
        queryset=KonovaCode.objects.filter(
            is_archived=False,
            is_leaf=True,
            code_lists__in=[CODELIST_CONSERVATION_OFFICE_ID],
        ),
        widget=autocomplete.ModelSelect2(
            url="codelist:conservation-office-autocomplete",
            attrs={
                "data-placeholder": _("Click for selection")
            }
        ),
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Generate report")
        self.form_caption = _("Select a timespan and the desired conservation office")
        self.action_url = reverse("analysis:reports")
        self.show_cancel_btn = False
        self.action_btn_label = _("Continue")

    def save(self) -> str:
        """ Generates a redirect url for the detail report

        Returns:
            detail_report_url (str): The constructed detail report url

        """
        date_from = self.cleaned_data.get("date_from", None)
        date_to = self.cleaned_data.get("date_to", None)
        office = self.cleaned_data.get("conservation_office", None)
        detail_report_url = reverse("analysis:report-detail", args=(office.id,)) + f"?df={date_from}&dt={date_to}"
        return detail_report_url
