import logging
from datetime import timedelta
from django.utils import timezone
from celery import task

from payments.models import Payment
from .models import Payment, Subscription, ACTIVE_BACKENDS

logger = logging.getLogger(__name__)

@task
def check_subscriptions():
    logger.debug("checking subscriptions")
    subs = Subscription.objects.filter(status='active', backend_id='stripe').all()
    for sub in subs:
        logger.debug("checking subscription #%s on %s", sub.id, sub.backend_id)
        sub.refresh_from_db()
        ACTIVE_BACKENDS['stripe'].refresh_subscription(sub)
        sub.save()

@task
def cancel_old_payments():
    expdate = timezone.now() - timedelta(days=3)

    expired = Payment.objects.filter(created__lte=expdate, status='new',
                                     paid_amount=0)

    logger.info("cancelling %d pending payments older than 3 days (%s)", len(expired), expdate.isoformat())

    for p in expired:
        logger.debug("cancelling payment #%d (%s): created on %s", p.id, p.user.username, p.created)
        p.status = 'cancelled'
        p.save()
