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

"""
import collections

from django.core.exceptions import ImproperlyConfigured

from codelist.settings import CODELIST_BIOTOPES_ID, \
    CODELIST_BIOTOPES_EXTRA_CODES_FULL_ID
from codelist.autocomplete.base import KonovaCodeAutocomplete
from konova.utils.message_templates import UNGROUPED


class BiotopeCodeAutocomplete(KonovaCodeAutocomplete):
    """
    Due to limitations of the django dal package, we need to subclass for each code list
    """
    group_by_related = "parent"
    related_field_name = "long_name"

    def __init__(self, *args, **kwargs):
        self.c = CODELIST_BIOTOPES_ID
        super().__init__(*args, **kwargs)

    def order_by(self, qs):
        """ Orders by a predefined value

        Wrapped in a function to provide inheritance-based different orders

        Args:
            qs (QuerySet): The queryset to be ordered

        Returns:
            qs (QuerySet): The ordered queryset
        """
        return qs.order_by(
            "short_name",
        )

    def get_result_label(self, result):
        return f"{result.long_name} ({result.short_name})"

    def get_results(self, context):
        """Return the options grouped by a common related model.

        Raises ImproperlyConfigured if self.group_by_name is not configured
        """
        if not self.group_by_related:
            raise ImproperlyConfigured("Missing group_by_related.")

        super_groups = collections.OrderedDict()

        object_list = context['object_list']

        for result in object_list:
            group = result.parent if result.parent else None
            group_name = f"{group.long_name} ({group.short_name})" if group else UNGROUPED
            super_group = result.parent.parent if result.parent else None
            super_group_name = f"{super_group.long_name} ({super_group.short_name})" if super_group else UNGROUPED
            super_groups.setdefault(super_group_name, {})
            super_groups[super_group_name].setdefault(group_name, [])
            super_groups[super_group_name][group_name].append(result)

        return [{
            'id': None,
            'text': super_group,
            'children': [{
                "id": None,
                "text": group,
                "children": [{
                    'id': self.get_result_value(result),
                    'text': self.get_result_label(result),
                    'selected_text': self.get_selected_result_label(result),
                } for result in results]
            } for group, results in groups.items()]
        } for super_group, groups in super_groups.items()]


class BiotopeExtraCodeAutocomplete(KonovaCodeAutocomplete):
    """
    Due to limitations of the django dal package, we need to subclass for each code list
    """
    group_by_related = "parent"
    related_field_name = "short_name"
    paginate_by = 200

    def __init__(self, *args, **kwargs):
        self.c = CODELIST_BIOTOPES_EXTRA_CODES_FULL_ID
        super().__init__(*args, **kwargs)

    def order_by(self, qs):
        """ Orders by a predefined value

        Wrapped in a function to provide inheritance-based different orders

        Args:
            qs (QuerySet): The queryset to be ordered

        Returns:
            qs (QuerySet): The ordered queryset
        """
        return qs.order_by(
            "short_name",
        )

    def get_result_label(self, result):
        return f"{result.long_name} ({result.short_name})"

    def get_selected_result_label(self, result):
        return f"{result.parent.short_name} > {result.long_name} ({result.short_name})"