from celery import task
from celery.utils.log import get_task_logger
from celery.exceptions import SoftTimeLimitExceeded
from django.db.models import Max

from go_http.send import HttpApiSender
import control.settings as settings
from subscription.models import Subscription, Message

logger = get_task_logger(__name__)


@task()
def process_message_queue(schedule):
    # Get all active and incomplete subscribers for schedule
    with Subscription.objects.filter(
        schedule=schedule, active=True, completed=False, in_process=0).all() as subscribers:
        if subscribers.exists():
            # Make a reusable session to Vumi
            sender = HttpApiSender(
                account_key=settings.VUMI_GO_ACCOUNT_KEY,
                conversation_key=settings.VUMI_GO_CONVERSATION_KEY,
                conversation_token=settings.VUMI_GO_ACCOUNT_TOKEN
            )
            # Fire off message processor for each
            for subscriber in subscribers:
                subscriber.in_process = 1
                subscriber.save()
                processes_message.delay(subscriber, sender)
        return subscribers.count()

@task()
def processes_message(subscriber, sender):
    try:
        # Get next message
        message = Message.objects.get(
            message_set=subscriber.message_set, lang=subscriber.lang,
            sequence_number=subscriber.next_sequence_number)
        # Send message
        response = sender.send_text(subscriber.to_addr, message.content)
        # Post process moving to next message, next set or finished
        # Get set max
        set_max = Message.objects.all().aggregate(Max('sequence_number'))["sequence_number__max"]
        # Compare user position to max
        if subscriber.next_sequence_number == set_max:
            # Mark current as completed
            subscriber.completed = True
            subscriber.active = False
            subscriber.save()
            # If next set defined create new subscription
            message_set = subscriber.message_set
            if message_set.next_set:
                # clone existing minus PK as recommended in
                # https://docs.djangoproject.com/en/1.6/topics/db/queries/#copying-model-instances
                subscriber.pk = None
                subscriber.in_process = 0
                subscription = subscriber
                subscription.message_set = message_set.next_set
                subscription.save()
        else:
            # More in this set so interate by one
            subscriber.next_sequence_number = subscriber.next_sequence_number + 1
            subscriber.in_process = 0
            subscriber.save()
        return response
    except SoftTimeLimitExceeded:
        logger.error('Soft time limit exceed processing message to Vumi HTTP API via Celery', exc_info=True)


@@ -516,26 +516,30 @@
 =False, 
-in_
 process
+_status
 =0).all(
@@ -997,26 +997,30 @@
 scriber.
-in_
 process
+_status
  = 1%0A   
@@ -2292,34 +2292,38 @@
  subscriber.
-in_
 process
+_status
  = 0%0A       
@@ -2630,18 +2630,22 @@
 ber.
-in_
 process
+_status
  = 0

Fix subscription filter variable