from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.utils.translation import gettext_lazy as _

from .permissions import ADMINISTRATE_MEMBERS
from .selectors import get_member
from .selectors import get_members
from .selectors import get_memberships
from .selectors import get_subscription_periods
from utils.view_utils import render
from utils.view_utils import render_list
from utils.view_utils import RowAction


@login_required
def membership_overview(request):
    memberships = get_memberships(member=request.user)
    current_membership = memberships.current()
    previous_memberships = memberships.previous()

    current_period = current_membership.period.period if current_membership else None

    context = {
        "current_membership": current_membership,
        "current_period": current_period,
        "previous_memberships": previous_memberships,
    }

    return render(
        request=request,
        template_name="membership/membership_overview.html",
        context=context,
    )


@login_required
@permission_required(ADMINISTRATE_MEMBERS.path)
def members_admin(request):
    users = get_members()

    return render_list(
        entity_name="member",
        entity_name_plural="members",
        request=request,
        paginate_by=20,
        objects=users,
        columns=[
            ("username", _("Username")),
            ("first_name", _("First name")),
            ("last_name", _("Last name")),
            ("email", _("Email")),
            ("active_membership", _("Active membership")),
        ],
        row_actions=[
            RowAction(
                label=_("View"),
                url_name="admin-members-detail",
                url_kwargs={"member_id": "id"},
            ),
        ],
    )


@login_required
@permission_required(ADMINISTRATE_MEMBERS.path)
def members_admin_detail(request, member_id):
    member = get_member(member_id=member_id)
    subscription_periods = get_subscription_periods(member=member)

    context = {
        "member": member,
        "subscription_periods": subscription_periods,
        "base_path": "admin-members",
    }

    return render(
        request=request,
        template_name="membership/members_admin_detail.html",
        context=context,
    )
