# chat/consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json

from core.tools import translate_text


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # print(self.scope["session"]["_auth_user_id"])
        print("here connect method started!")
        # user_id = self.scope["session"]["_auth_user_id"]
        user_id = self.scope['user']
        if user_id.is_anonymous:
            await self.disconnect(0)
        else:
            print("user_id first is ::::::, ", user_id)
            user_id = user_id.id
            print("user_id is::::::", user_id)
            self.group_name = "{}".format(user_id)
            # Join room group
            await self.channel_layer.group_add(self.group_name, self.channel_name)
            await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    # Receive message from WebSocket
    async def receive(self, text_data=None, bytes_data=None):

        text_data_json = json.loads(text_data)
        message = text_data_json["message"]
        # print("msg is: ", message)
        # message = translate_text(message)
        # Send message to room group
        await self.channel_layer.group_send(
            self.chat_group_name, {"type": "recieve_group_message", "message": message}
        )

    async def recieve_group_message(self, event):
        message = event["message"]
        # print("msg is: ", message)

        # message = translate_text(message)
        # Send message to WebSocket
        await self.send(text_data=json.dumps({"message": message}))
