import logging

from celery import shared_task
from django.core.cache import caches

from devices.constants import CACHE_TIMEOUT
from devices.models.sensor import ArmaSensor
from devices.serializers.sensor_serializers import SensorSerializer
from devices.services.sensor.enums import SystemMessage
from devices.services.sensor.rabbitmq import SensorManagement

_log = logging.getLogger(__name__)


@shared_task
def ping_sensors():

    # make all sensors offline
    all_sensors_id = [sensor for sensor in ArmaSensor.objects.values_list('id', flat=True)]
    redis_data = {f'sensor_{sensor_id}_status': {'status': 'offline'} for sensor_id in all_sensors_id}
    caches['redis'].set_many(redis_data, CACHE_TIMEOUT)

    # set new sensor status
    sensors_responses = SensorManagement().send_message(message_type=SystemMessage.ping, wait_response=True)
    for response in sensors_responses:
        _log.debug(f'Sensor response: {response}')
        sensor = ArmaSensor.objects.get(uuid=response['uuid'])
        if not response['synchronization'] or not sensor.synchronization:
            data = SensorSerializer(instance=sensor).data
            sync_response = SensorManagement().send_message(
                sensor=sensor,
                message_type=SystemMessage.synchronization,
                body=data,
                wait_response=True
            )

            if sync_response.get('synchronization', None):
                sensor.synchronization = True
                sensor.save()
            else:
                _log.warning(f'Sensor {response["uuid"]} not synchronized: {sync_response}')
        caches['redis'].set(f'sensor_{sensor.pk}_status', {'status': 'online'}, CACHE_TIMEOUT)
