from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.forms import model_to_dict

from .consts import WS_USER_DEVICES_GROUP, WS_FACTORY_DEVICES_GROUP
from sandbox.apps.devices.models import Device


def _object_to_json(o):
    """
    Convert Device object to json, which will nbe sent to WebSocket
    """
    _json = model_to_dict(o, exclude='card_request')
    return _json


def ws_send_factory_devices(*args):
    channel_layer = get_channel_layer()
    devices = [_object_to_json(d) for d in Device.objects.all() if d.is_factory_device]
    async_to_sync(channel_layer.group_send)(
        WS_FACTORY_DEVICES_GROUP,
        {
            'type': 'send_devices_json',
            'devices': devices
        }
    )


def ws_send_user_devices(*args):
    channel_layer = get_channel_layer()
    devices = [_object_to_json(d) for d in Device.objects.all() if d.is_user_device]
    async_to_sync(channel_layer.group_send)(
        WS_USER_DEVICES_GROUP,
        {
            'type': 'send_devices_json',
            'devices': devices
        }
    )
