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

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

from intervention.filters import InterventionTableFilter
from intervention.models import Intervention
from konova.utils.message_templates import DATA_CHECKED_ON_TEMPLATE, DATA_IS_UNCHECKED, DATA_CHECKED_PREVIOUSLY_TEMPLATE
from konova.utils.tables import BaseTable, TableRenderMixin, TableOrderMixin
import django_tables2 as tables


class InterventionTable(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",
        attrs={
            "th": {
                "class": "w-25",
            }
        }
    )
    c = tables.Column(
        verbose_name=_("Checked"),
        orderable=True,
        empty_values=[],
        accessor="checked",
    )
    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 = _("Interventions")
        self.add_new_url = reverse("intervention:new")
        qs = kwargs.get("queryset", None)
        self.filter = InterventionTableFilter(
            user=request.user,
            data=request.GET,
            queryset=qs,
        )
        kwargs["queryset"] = self.filter.qs
        super().__init__(request, *args, **kwargs)

    def render_id(self, value, record: Intervention):
        """ Renders the id column for an intervention

        Args:
            value (str): The identifier value
            record (Intervention): The intervention record

        Returns:

        """
        context = {
            "tooltip": _("Open {}").format(_("Intervention")),
            "content": value,
            "url": reverse("intervention:detail", args=(record.id,)),
            "has_revocations": record.legal.revocations.exists()
        }
        html = render_to_string(
            "table/revocation_warning_col.html",
            context
        )
        return html

    def render_c(self, value, record: Intervention):
        """ Renders the checked column for an intervention

        Args:
            value (str): The identifier value
            record (Intervention): The intervention record

        Returns:

        """
        html = ""
        checked = value is not None
        previously_checked = record.get_last_checked_action()
        tooltip = DATA_IS_UNCHECKED
        if checked:
            checked_on = value.get_timestamp_str_formatted()
            tooltip = DATA_CHECKED_ON_TEMPLATE.format(checked_on, record.checked.user)
        html += self.render_checked_star(
            tooltip=tooltip,
            icn_filled=checked,
        )
        if previously_checked and not checked:
            checked_on = previously_checked.get_timestamp_str_formatted()
            tooltip = DATA_CHECKED_PREVIOUSLY_TEMPLATE.format(checked_on, previously_checked.user)
            html += self.render_previously_checked_star(
                tooltip=tooltip,
            )
        return format_html(html, None)

    def render_r(self, value, record: Intervention):
        """ Renders the recorded column for an intervention

        Args:
            value (str): The identifier value
            record (Intervention): The intervention record

        Returns:

        """
        html = ""
        checked = value is not None
        tooltip = _("Not recorded 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, None)

