from .models import Notification, NotificationType, UserNotificationPreference
from .utils import send_html_email, send_sms, send_whatsapp

def send_notification(user, type_key, context={}, message=None):
    ntype = NotificationType.objects.filter(key=type_key, is_active=True).first()
    if not ntype:
        return
    # print('-------------------- user notification filtered -------------------')
    prefs = UserNotificationPreference.objects.filter(user=user, notification_type=ntype).first()
    # print('-------------------- notification object created -------------------')
    if ntype.enabled_inapp and (not prefs or prefs.inapp):
        Notification.objects.create(user=user, type=ntype, message=message or ntype.label)
    # print('-------------------- send email check  -------------------')
    # print(ntype.enabled_email)
    # print(not prefs)
    # print(prefs.email)
    # print((not prefs or prefs.email))
    # print(ntype.enabled_email and (not prefs or prefs.email))
    if ntype.enabled_email and (not prefs or prefs.email):
        # print('-------------------- send email notification  -------------------')
        # print(ntype.email_template)
        if ntype.email_template:
            try:
                send_html_email(ntype.label, user.email, ntype.email_template, context)
                # print("email sent")
            except Exception as e:
                print(" Email send failed:", e)
    # print('-------------------- send sms notification  -------------------')
    if ntype.enabled_sms and (not prefs or prefs.sms):
        if ntype.sms_template:
            send_sms(user.profile.mobile, ntype.sms_template, context)

    # print('-------------------- send whatsapp notification  -------------------')
    if ntype.enabled_whatsapp and (not prefs or prefs.whatsapp):
        if ntype.whatsapp_template:
            send_whatsapp(user.profile.mobile, ntype.whatsapp_template, context)
