from channels.generic.websocket import AsyncWebsocketConsumer
import json
import logging
from homelog import settings

LOGGER = logging.getLogger(__name__)


class BookerFeConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        self.scanner_id = self.scope['url_route']['kwargs']['scanner_id']
        self.scanner_group_name = self.scanner_id
        self.group_name = self.scanner_group_name
        #self.group_name = settings.MQTT_CHANNEL_NAME
        # join to group
        await self.channel_layer.group_add(self.scanner_group_name, self.channel_name)
        topic = f"barcodescanner/{self.scanner_id}/scan"
        LOGGER.debug(f"send mqtt_subscribe topic {topic} to channel group {self.scanner_group_name} (my channel is {self.channel_name})")
        await self.channel_layer.send(settings.MQTT_CHANNEL_NAME, {
            "type": "mqtt.subscribe",
            "topic": topic,
            "group": self.scanner_group_name
        })
        await self.accept()

    async def disconnect(self):
        # leave group
        await self.channel_layer.group_discard(self.group_name, self.channel_name)
        LOGGER.debug(f"disconnect from channel group {self.group_name}")

    async def receive(self, text_data):
        print('>>>', text_data)
        msg = '{"message":"pong!"}' if text_data == '{"message":"ping"}' else text_data
        print('<<<', msg)
        await self.channel_layer.group_send(
            self.scanner_group_name,
            {
                'type': 'distribute',
                'text': msg
            }
        )

    async def distribute(self, event):
        valother = event['text']
        LOGGER.debug(f"distribute text={valother}")
        await self.send(text_data=valother)

    async def mqtt_message(self, event):
        message = event['message']
        topic = message['topic']
        payload = message['payload']
        LOGGER.debug(f"Received message with payload={payload}, topic={topic}")
        await self.send(text_data=json.dumps({'message': payload, 'topic': topic}))
