import logging
from random import randint

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.test import override_settings
from .uwsgi_compat import cron

from ocyan.main.loading import get_ocyan_class
from ocyan.main.utils import run_exclusive

get_default_site = get_ocyan_class("wagtail_utils.utils", "get_default_site")

logger = logging.getLogger(__name__)


# pylint: disable=unused-argument
@cron(randint(0, 59), -1, -1, -1, -1, target="spooler")  # every hour at random minute
def send_customer_alerts_async(args):
    # the spooler is forked so the db connection might be closed
    try:
        if not connection.is_usable():
            connection.close()
    except AttributeError:
        connection.close_if_unusable_or_obsolete()

    try:
        if not settings.SITE_ID:
            site = get_default_site()
            with override_settings(SITE_ID=site.pk):
                run_exclusive("oscar_send_alerts")
        else:
            run_exclusive("oscar_send_alerts")
    except ObjectDoesNotExist:
        logger.error(
            "The default site can not be found, make sure the hostname in the wagtail default site matches a django site"
        )
