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 random

__author__ = 'nick'

class Command(BaseCommand):

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

        apns = APNs(use_sandbox=getattr(settings, 'APNS_SANDBOX'), cert_file=getattr(settings, 'APNS_CERT_FILE'))
        survey_list_to_check = [5]
        date = timezone.now().replace(minute=0, second=0, microsecond=0)

        disabled_notifications = Participant.objects.filter(enable_notifications=0)
        participants = Participant.objects.raw("""
            SELECT DATEDIFF(CURDATE(), entry_date) AS date_diff, participant_id AS id FROM survey_observation, participant_participant WHERE participant_participant.id = survey_observation.participant_id AND DATEDIFF(CURDATE(), entry_date) < 32 AND participant_id NOT IN (%s)
            AND EXTRACT(HOUR FROM CONVERT_TZ(%s, 'UTC', participant_participant.timezone)) = 10 GROUP BY participant_id ORDER BY entry_date DESC""", 
            [",".join([str(participant.id) for participant in disabled_notifications]) if disabled_notifications.count() > 0 else "0",
            date.strftime('%Y-%m-%d %H:%M:%S')])
        print participants
        for participant in participants:
            message = None
            notification = None
            notify = False
            day = participant.date_diff
            if day == 2:
                message = "We miss you! Track to help endo research"
                notification = "2_days_missed_track"
            if day == 5:
                message = "Hey, remember us?"
                notification = "5_days_missed_tracked"
            if day == 10:
                message = "We hope you are feeling well!"
                notification = "10_days_missed_tracked"
            if day == 15:
                message = "Experiencing any endo symptoms?"
                notification = "15_days_missed_tracked"
            if day == 21:
                message = "How is your experience of endo today?"
                notification = "21_days_missed_tracked"
            if day == 31:
                message = "You didn't track anything last month. Want to track today?"
                notification = "31_days_missed_tracked"

            if notification and message:
                if not ParticipantNotificationsSent.objects.filter(
                    participant=participant,date=date,notification=notification).exists():
                    print "Notify {0}".format(participant.id)
                    if Participant.objects.get(id=participant.id).push_token:
                        payload = Payload(
                                        alert=message,
                                        sound="default",
                                        badge=1)
                        token_hex = Participant.objects.get(id=participant.id).push_token
                        apns.gateway_server.send_notification(token_hex, payload)
                        notify = True
                    if Participant.objects.get(id=participant.id).gcm_token:
                        registration_ids = [Participant.objects.get(id=participant.id).gcm_token]
                        FcmNotification().send_message(title="Notification", body=message, registration_ids=registration_ids)
                        notify = True
                    if notify:
                        notification = ParticipantNotificationsSent(participant=participant,date=date,notification=notification)
                        notification.save()
