from django.core.management import BaseCommand
from apns import APNs, Frame, Payload
import datetime
from django.utils import timezone
from participant.api import ParticipantApi
from participant.models import Participant
from participant.models import ParticipantNotificationsSent
from survey.api import ObservationApi
from django.conf import settings
import os
import logging
import random

__author__ = 'nick'

# 0   - No errors encountered
# 1   - Processing error
# 2   - Missing device token
# 3   - Missing topic
# 4   - Missing payload
# 5   - Invalid token size
# 6   - Invalid topic size
# 7   - Invalid payload size
# 8   - Invalid token
# 255 - None (unknown)

class Command(BaseCommand):

    def handle(self, *args, **kwargs):

        apns = APNs(use_sandbox=getattr(settings, 'APNS_SANDBOX'), cert_file=getattr(settings, 'APNS_CERT_FILE'))
        # Get feedback messages.
        for (token_hex, fail_time) in apns.feedback_server.items():
            try:
                print token_hex, fail_time
                p = Participant.objects.get(push_token=token_hex)
                print p.id
                p.push_token = None
                p.save()
            except:
                # Token does not exist
                pass