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 participant.views import FcmNotification
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)

def response_listener(error_response):
    print error_response
    id = error_response["identifier"]
    notification = ParticipantNotificationsSent.objects.get(id=id)
    notification.response_status = error_response["status"]
    notification.save()
apns = APNs(use_sandbox=getattr(settings, 'APNS_SANDBOX'), cert_file=getattr(settings, 'APNS_CERT_FILE'), enhanced=True)
apns.gateway_server.register_response_listener(response_listener)
class Command(BaseCommand):

    def add_arguments(self, parser, *args, **kwargs):
        parser.add_argument('-d', '--date',
            help='Date to use for notification. (YYYY-MM-DD',
            default=None,
            type=str)

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

        survey_list_to_check = [5]
        date = timezone.now().replace(minute=0, second=0, microsecond=0)
        # Random Notification
        participants = Participant.objects.raw("""
            SELECT id, survey_notification_time, push_token, NOW() AS _date, DATE(CONVERT_TZ(NOW(), 'UTC', participant_participant.timezone)) AS local_date FROM participant_participant
                WHERE HOUR(survey_notification_time) = {0} AND enable_notifications=1""".format(date.hour))
        for participant in participants:
            try:
                registration_ids = []
                if kwargs["date"] is None:
                    date = participant.local_date
                else:
                    date = datetime.datetime.strptime(kwargs["date"], "%Y-%m-%d")

                count = ParticipantNotificationsSent.objects.filter(
                    participant=participant,date=date,notification="survey_reminder").count()
                if count >= 1:
                    continue
                # Check survey
                observations = ObservationApi()._filter(
                    # survey_id_list=survey_list_to_check, 
                    start_date=date.strftime('%Y-%m-%d'),
                    end_date=(datetime.timedelta(days=1)+date).strftime('%Y-%m-%d'),
                    participant=participant.id)
                token_hex = participant.push_token
                gcm_token = participant.gcm_token
                if observations.count() == 0:
                    # Send a notification
                    alert=random.choice([
                            "Remember track your day!",
                            "We need your input! Tell us about your day!",
                            "Track your day to contribute to endo research!",
                            "Be the change you wish to see in the world. Track your day now!",
                            "Did you remember to track your day?",
                            "Your experience of endometriosis matters. Track your day now!",
                            "Tell Phendo about your endo experience today!",
                            "Remember to complete your tracking today",
                            "We need your input! Track your day!",
                            "Please track your day!"
                        ])
                    if token_hex or gcm_token:
                        notification = ParticipantNotificationsSent(participant=participant,date=date,notification="survey_reminder")
                        notification.save()
                        notification.date = date
                        notification.save()
                    if token_hex:
                        payload = Payload(
                        alert = alert,
                        sound="default",
                        badge=1)
                        apns.gateway_server.send_notification(token_hex, payload, identifier=notification.id)
                    if gcm_token:
                        registration_ids.append(gcm_token)
                        FcmNotification().send_message(title="Survey Reminder", body=alert, registration_ids=registration_ids)
            except Exception as e:
                log = logging.getLogger('notification_error')
                log.error("Notification Error : Participant {0}, Error : {1}".format(participant.id, e))
