"""File containing member application django tables."""

import django_tables2 as tables
from django.utils.translation import ugettext as _
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F, OuterRef, Subquery
from django.utils import timezone

from members.models import Member, Payment, Request


class MemberTable(tables.Table):
    """Table for member."""

    last_paid = tables.DateTimeColumn(verbose_name=_('Last paid'))

    options = tables.TemplateColumn(
        ('<a class="data-table-button btn btn-primary" '
            'href="/members/edit/{{ record.id }}">') + _('Edit') + '</a>', verbose_name=""
    )

    class Meta:
        """Meta for member table."""

        model = Member

    def render_last_paid(self, record):
        try:
            return timezone.localtime(record.payments.filter(member=record).latest('date').date).strftime('%-d.%-m.%Y %H:%M')
        except ObjectDoesNotExist:
            return timezone.localtime(record.created).strftime('%-d.%-m.%Y %H:%M') + _(" (not paid)")

    def order_last_paid(self, queryset, is_descending):
        queryset = Member.get_members_with_latest_payment(queryset).order_by(('-' if is_descending else '') + 'last_paid')
        return (queryset, True)


class PaymentTable(tables.Table):
    """Table for payments."""

    member = tables.Column(accessor='member', verbose_name=_('Member'))

    options = tables.TemplateColumn(
        ('<a class="data-table-button btn btn-primary" '
            'href="/members/edit_payment/{{ record.id }}">') + _('Edit') + '</a>',
        verbose_name=""
    )

    class Meta:
        """Meta for payment table."""

        model = Payment


class RequestTable(tables.Table):
    """Table for member applications."""

    options = tables.TemplateColumn(
        ('<a class="data-table-button btn btn-primary" '
            'href="/members/edit_application/{{ record.id }}">') + _('Edit') + '</a>',
        verbose_name=""
    )

    class Meta:
        """Meta for request table."""

        model = Request
