import datetime
import pytz
from .notification_hook import NotificationHook

from aitrainer_backoffice.aitrainer_backoffice.models import notification as notif    


from ..models.notification import NotificationHistory
from .fcm import FCM
import traceback

class Notification:
    fcm = FCM()

    def run(self):  
        print("** Running Notification automation")
        notification_queryset = notif.Notification.objects.using('live').raw('SELECT * from notification WHERE active = 1')
        
        for notification in notification_queryset:
            if notification.schedule_date != None:
                pass
            elif notification.schedule_hook != None:
                hook = NotificationHook()
                try: 
                    hook_function = notification.schedule_hook
                    hook_sql = notification.schedule_sql
                    if hook_sql == None:
                        customers = getattr(hook, hook_function)()
                    else:
                        customers = getattr(hook, hook_function)(hook_sql)

                    print(f' --- Count of notifying customers: {len(list(customers))} --- ')
                    for customer in customers:                        
                        if customer.firebase_reg_token != None and customer.customer_id != None:                            
                            print(f'-- Notify Customer {customer.customer_id}')
                            rc= self.fcm.send_to_token(notification.message_title, notification.message_body, notification.image_url, customer.firebase_reg_token)
                            self.insert_history(notification=notification, customer=customer, rc=rc)
                            
                            
                except Exception as ex: 
                    print(f'Error in execution of the notification {notification.internal_name}: {ex}')
                    traceback.print_exc()

    def insert_history(self, notification, customer, rc):
        history = NotificationHistory()
        history.pk = None
        history.notification = notification
        history.customer = customer
        history.response = rc
        cet = pytz.timezone('Europe/Budapest')
        history.notification_date = datetime.datetime.now(tz=cet)
        history.save()
        print(f'-- Notification History "{history}" has been saved')