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)
        checks = [
            {"month": 1, "message": "You've had 1 month with Phendo. Keep tracking!", "id": "1_month_tracked"},
            {"month": 2, "message": "2 months tracked! Keep it up for 1 more!", "id": "2_month_tracked"},
            {"month": 3, "message": "3 months tracked! You are AWESOME!", "id": "3_month_tracked"}
        ]
        for i in checks:
            # Random Notification
            participants = Participant.objects.raw("""
            SELECT TIMESTAMPDIFF(MONTH, join_date, CURDATE()) AS diff, id FROM participant_participant WHERE TIMESTAMPDIFF(MONTH, join_date, CURDATE()) > %s AND id NOT IN (%s) AND EXTRACT(HOUR FROM CONVERT_TZ(%s, 'UTC', timezone)) = 8""", 
            [
                i["month"],
                ",".join([
                        str(participant.id) for participant in disabled_notifications]) 
                            if disabled_notifications.count() > 0 else "0",
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            ])
            for participant in participants:
                # latest activity
                notify = False
                _p = Participant.objects.raw("""
                    SELECT DATEDIFF(CURDATE(), entry_date) AS date_diff, participant_id AS id FROM survey_observation WHERE participant_id = %s ORDER BY DATEDIFF(CURDATE(), entry_date) ASC LIMIT 1""",
                    [participant.id])[0]

                if _p.date_diff <= 7:
                    if not ParticipantNotificationsSent.objects.filter(participant=participant,date=date,notification=i["id"]).exists():
                        if Participant.objects.get(id=participant.id).push_token:
                            payload = Payload(
                                            alert=i["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="Monthly Reminder", body=i["message"], registration_ids=registration_ids)
                            notify = True
                        if notify:
                            notification = ParticipantNotificationsSent(participant=participant,date=date,notification=i["id"])
                            notification.save()
