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

"""
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.formats import number_format
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

from compensation.filters.eco_account import EcoAccountTableFilter
from compensation.models import EcoAccount
from konova.utils.tables import TableRenderMixin, BaseTable, TableOrderMixin

import django_tables2 as tables


class EcoAccountTable(BaseTable, TableRenderMixin, TableOrderMixin):
    id = tables.Column(
        verbose_name=_("Identifier"),
        orderable=True,
        accessor="identifier",
    )
    t = tables.Column(
        verbose_name=_("Title"),
        orderable=True,
        accessor="title",
    )
    d = tables.Column(
        verbose_name=_("Parcel gmrkng"),
        orderable=False,
        accessor="geometry",
    )
    av = tables.Column(
        verbose_name=_("Available"),
        orderable=True,
        accessor="deductable_rest",
        attrs={
            "th": {
                "class": "w-20",
            }
        }
    )
    r = tables.Column(
        verbose_name=_("Recorded"),
        orderable=True,
        empty_values=[],
        accessor="recorded",
    )
    e = tables.Column(
        verbose_name=_("Editable"),
        orderable=True,
        empty_values=[],
        accessor="users",
    )
    lm = tables.Column(
        verbose_name=_("Last edit"),
        orderable=True,
        accessor="modified__timestamp",
    )

    class Meta(BaseTable.Meta):
        template_name = "django_tables2/bootstrap4.html"

    def __init__(self,  request: HttpRequest, *args, **kwargs):
        self.title = _("Eco Accounts")
        self.add_new_url = reverse("compensation:acc:new")
        qs = kwargs.get("queryset", None)
        self.filter = EcoAccountTableFilter(
            user=request.user,
            data=request.GET,
            queryset=qs,
        )
        kwargs["queryset"] = self.filter.qs
        super().__init__(request, *args, **kwargs)

    def render_id(self, value, record: EcoAccount):
        """ Renders the id column for an eco account

        Args:
            value (str): The identifier value
            record (EcoAccount): The eco account record

        Returns:

        """
        html = ""
        html += self.render_link(
            tooltip=_("Open {}").format(_("Eco-account")),
            href=reverse("compensation:acc:detail", args=(record.id,)),
            txt=value,
            new_tab=False,
        )
        return format_html(html)

    def render_av(self, value, record: EcoAccount):
        """ Renders the available column for an eco account

        Args:
            value (float): The deductable_rest
            record (EcoAccount): The eco account record

        Returns:

        """
        try:
            value_relative = record.get_deductable_rest_relative()
        except ZeroDivisionError:
            value_relative = 0
        html = render_to_string("konova/widgets/progressbar.html", {"value": value_relative})
        html += f"{number_format(record.deductable_rest, decimal_pos=2)} m²"
        return format_html(html)

    def render_r(self, value, record: EcoAccount):
        """ Renders the recorded column for an eco account

        Args:
            value (str): The identifier value
            record (EcoAccount): The eco account record

        Returns:

        """
        html = ""
        checked = value is not None
        tooltip = _("Not recorded yet. Can not be used for deductions, yet.")
        if checked:
            on = value.get_timestamp_str_formatted()
            tooltip = _("Recorded on {} by {}").format(on, record.recorded.user)
        html += self.render_bookmark(
            tooltip=tooltip,
            icn_filled=checked,
        )
        return format_html(html)
