"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 16.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_COMPENSATION_ACTION_ID, CODELIST_COMPENSATION_ACTION_DETAIL_ID
from konova.models import BaseResource


class UnitChoices(models.TextChoices):
    """
    Predefines units for selection
    """
    cm = "cm", _("cm")
    m = "m", _("m")
    m2 = "m2", _("m²")
    m3 = "m3", _("m³")
    km = "km", _("km")
    ha = "ha", _("ha")
    st = "pcs", _("Pieces")  # pieces


class CompensationAction(BaseResource):
    """
    Compensations include actions like planting trees, refreshing rivers and so on.
    """
    action_type = models.ManyToManyField(
        KonovaCode,
        blank=True,
        limit_choices_to={
            "code_lists__in": [CODELIST_COMPENSATION_ACTION_ID],
            "is_selectable": True,
            "is_archived": False,
        },
        related_name='+',
    )
    action_type_details = models.ManyToManyField(
        KonovaCode,
        blank=True,
        limit_choices_to={
            "code_lists__in": [CODELIST_COMPENSATION_ACTION_DETAIL_ID],
            "is_selectable": True,
            "is_archived": False,
        },
        related_name='+',
    )
    amount = models.FloatField()
    unit = models.CharField(max_length=100, null=True, blank=True, choices=UnitChoices.choices)
    comment = models.TextField(blank=True, null=True, help_text="Additional comment")

    def __str__(self):
        return f"{self.action_type.all()} | {self.amount} {self.unit}"

    @property
    def unit_humanize(self):
        """ Returns humanized version of enum

        Used for template rendering

        Returns:

        """
        choices = UnitChoices.choices
        for choice in choices:
            if choice[0] == self.unit:
                return choice[1]
        return None
