from django.db import models

from ajabsacco.core.codes import loans as loan_codes

from django.utils import timezone

import datetime
import calendar

from django.db.models.loading import get_model

from django.db.models import Q, Sum, Count

class MembersQuerySet(models.QuerySet):
    #By Date
    def this_week(self, *args, **kwargs):
        today = timezone.now()

        time_range = (
            (today - datetime.timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
            (today + datetime.timedelta(days=7)).replace(hour=23, minute=59, second=59, microsecond=999999)
        )
        return self.in_date_range(time_range[0], time_range[1], last_day_of_week)

    def this_month(self, *args, **kwargs):
        today = timezone.now()
        return self.in_month(today, *args, **kwargs)

    def in_month(self, date, *args, **kwargs):        
        days_in_month = calendar.monthrange(date.year, date.month)[1]
        time_range = (
            date.replace(day=1, hour=0, minute=0, second=0, microsecond=0),
            date.replace(day=days_in_month, hour=23, minute=59, second=59, microsecond=999999)
        )

        return self.in_date_range(time_range[0], time_range[1], *args, **kwargs)

    def today(self, *args, **kwargs):
        today = timezone.now()
        time_range = (
            today.replace(hour=0, minute=0, second=0, microsecond=0),
            today.replace(hour=23, minute=59, second=59, microsecond=999999)
        )
        return self.in_date_range(time_range[0], time_range[1], *args, **kwargs)

    def in_date_range(self, start_date, end_date, *args, **kwargs):
        return self.filter(
            Q(date_joined__gte=start_date) & Q(date_joined__lte=end_date),
            *args, **kwargs
        )
    