"""
Staff panel data scoping.

A staff member is a collection agent assigned to one or more places
(Staff.places). Everything the staff panel lists or changes is limited to
loans of those places. A staff member with no place assigned sees nothing.
"""
from django.http import Http404

from NexusApp.models import Customer, Loan, LoanPayment, Place


def staff_place_ids(staff):
    if staff is None:
        return []
    cached = getattr(staff, '_place_ids_cache', None)
    if cached is None:
        cached = list(staff.places.values_list('id', flat=True))
        staff._place_ids_cache = cached
    return cached


def staff_places(request):
    return Place.objects.filter(id__in=staff_place_ids(getattr(request, 'staff', None)))


def staff_loans(request, qs=None):
    qs = Loan.objects.all() if qs is None else qs
    return qs.filter(place_id__in=staff_place_ids(getattr(request, 'staff', None)))


def staff_payments(request, qs=None):
    qs = LoanPayment.objects.all() if qs is None else qs
    return qs.filter(loan__place_id__in=staff_place_ids(getattr(request, 'staff', None)))


def staff_customers(request, qs=None):
    qs = Customer.objects.all() if qs is None else qs
    return qs.filter(
        id__in=staff_loans(request).values('customer_id')
    )


def staff_can_access_place(request, place_id):
    try:
        return int(place_id) in staff_place_ids(getattr(request, 'staff', None))
    except (TypeError, ValueError):
        return False


def get_staff_place_or_404(request, place_id):
    if not staff_can_access_place(request, place_id):
        raise Http404('Place not found')
    return Place.objects.get(pk=place_id)


def get_staff_loan_or_404(request, loan_id, qs=None):
    try:
        return staff_loans(request, qs).get(pk=int(loan_id))
    except (Loan.DoesNotExist, TypeError, ValueError):
        raise Http404('Loan not found')
