# Tasks for syncing via Concordia MQ
from celery import shared_task
from django.conf import settings
from lc_celery_beat.task_classes import LCSingleton

from ..channels import ROOM_CHANNEL_REGISTRY
from .publishing import schedule_publish_local_events_to_concord_room


@shared_task(base=LCSingleton, lock_expiry=43200, raise_on_duplicate=True)
def confirm_events_synced():
    """
    The TriggerChannel listener may not have been running, a task may
    have failed, so some Events may not be marked as synchronized.

    This task is to ensure that all ConcordEvent model records will
    be synchronized. It should be run on a recurring basis.
    """
    if settings.SYNC_PUBLISHER:
        return

    for channel_name, trigger_channel in ROOM_CHANNEL_REGISTRY.items():
        EventModel = trigger_channel.model
        for record in EventModel.objects.unsynced().distinct('phg_obj_id'):
            schedule_publish_local_events_to_concord_room(
                channel=trigger_channel,
                data=record.pgh_data,
            )


__all__ = [
    'confirm_events_synced',
]
