import logging

from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer

from sandbox.apps.devices.core.ws import ws_send_user_devices, ws_send_factory_devices


class _Base(JsonWebsocketConsumer):
    def connect(self):
        logging.debug(f'### New connection: {self.__class__.__name__} ###')
        self.accept()
        async_to_sync(self.channel_layer.group_add)(
            self.GROUP_NAME,
            self.channel_name
        )
        self.on_connect()

    def receive(self, text_data=None, bytes_data=None, **kwargs):
        pass

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.GROUP_NAME,
            self.channel_name
        )
        self.close()
        logging.debug(f'### Disconnected: {self.__class__.__name__} ###')

    def send_devices_json(self, event):
        devices = event['devices']
        self.send_json(devices)


class FactoryDevicesConsumer(_Base):
    GROUP_NAME = 'factory_devices'
    on_connect = ws_send_factory_devices


class UserDevicesConsumer(_Base):
    GROUP_NAME = 'user_devices'
    on_connect = ws_send_user_devices
