import logging
import os

import firebase_admin
from django.conf import settings
from firebase_admin import credentials, messaging

from config.settings.base import env
from {{project_slug}}.devices.models import PersonalDevice

logger = logging.getLogger("console")

settings_file = env("DJANGO_SETTINGS_MODULE")

if settings_file != "config.settings.test":
    FIREBASE_CREDENTIALS = os.path.join(settings.BASE_DIR, "firebase-adminsdk.json")

    cred = credentials.Certificate(FIREBASE_CREDENTIALS)
    firebase_admin.initialize_app(cred)


def get_user_devices_tokens(user):
    if settings_file != "config.settings.test":
        return []
    devices = PersonalDevice.objects.filter(user=user).values_list("token", flat=True)
    tokens = []
    for device in devices:
        tokens.append(device)
    return tokens


def send_notification(title, msg, devices: list):
    if settings_file != "config.settings.test":
        return
    if not devices:
        logging.info(f"No message send because there is no device")
        return
    message = messaging.MulticastMessage(
        notification=messaging.Notification(title=title, body=msg), tokens=devices
    )

    response = messaging.send_each_for_multicast(message)

    logger.info(f"messaging response: {response}")
