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

"""
from django.db import models
from django.utils.translation import gettext_lazy as _

from codelist.models import KonovaCode
from codelist.settings import CODELIST_CONSERVATION_OFFICE_ID, CODELIST_REGISTRATION_OFFICE_ID, \
    CODELIST_HANDLER_ID
from konova.models import UuidModel
from konova.utils.message_templates import UNKNOWN, NO_DETAILS


class Handler(UuidModel):
    """ The handler of an entry

    Refers to 'Eingriffsverursacher' or 'Maßnahmenträger'

    """
    type = models.ForeignKey(
        KonovaCode,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        limit_choices_to={
            "code_lists__in": [CODELIST_HANDLER_ID],
            "is_selectable": True,
            "is_archived": False,
        }
    )
    detail = models.CharField(
        max_length=500,
        null=True,
        blank=True,
    )

    def __str__(self):
        detail = self.detail or NO_DETAILS
        _type = self.type.long_name if self.type is not None else UNKNOWN
        return f'{_type}, {detail}'


class Responsibility(UuidModel):
    """
    Holds intervention data about responsible organizations and their file numbers for this case

    """
    registration_office = models.ForeignKey(
        KonovaCode,
        on_delete=models.SET_NULL,
        null=True,
        related_name="+",
        blank=True,
        limit_choices_to={
            "code_lists__in": [CODELIST_REGISTRATION_OFFICE_ID],
            "is_selectable": True,
            "is_archived": False,
        }
    )
    registration_file_number = models.CharField(max_length=1000, blank=True, null=True)
    conservation_office = models.ForeignKey(
        KonovaCode,
        on_delete=models.SET_NULL,
        null=True,
        related_name="+",
        blank=True,
        limit_choices_to={
            "code_lists__in": [CODELIST_CONSERVATION_OFFICE_ID],
            "is_selectable": True,
            "is_archived": False,
        }
    )
    conservation_file_number = models.CharField(max_length=1000, blank=True, null=True)
    handler = models.ForeignKey(
        Handler,
        null=True,
        blank=True,
        help_text="Refers to 'Eingriffsverursacher' or 'Maßnahmenträger'",
        on_delete=models.SET_NULL,
    )

    def __str__(self):
        return "ZB: {} | ETS: {} | Handler: {}".format(
            self.registration_office,
            self.conservation_office,
            str(self.handler)
        )
