from snek.system.model import now
from snek.system.service import BaseService


class ChatService(BaseService):

    async def finalize(self, message_uid):
        channel_message = await self.services.channel_message.get(uid=message_uid)
        channel_message["is_final"] = True
        await self.services.channel_message.save(channel_message)
        user = await self.services.user.get(uid=channel_message["user_uid"])
        channel = await self.services.channel.get(uid=channel_message["channel_uid"])
        channel["last_message_on"] = now()
        await self.services.channel.save(channel)
        await self.services.socket.broadcast(
            channel["uid"],
            {
                "message": channel_message["message"],
                "html": channel_message["html"],
                "user_uid": user["uid"],
                "color": user["color"],
                "channel_uid": channel["uid"],
                "created_at": channel_message["created_at"],
                "updated_at": channel_message["updated_at"],
                "username": user["username"],
                "uid": channel_message["uid"],
                "user_nick": user["nick"],
                "is_final": channel_message["is_final"],
            },
        )
        await self.app.create_task(
            self.services.notification.create_channel_message(message_uid)
        )

    async def send(self, user_uid, channel_uid, message, is_final=True):
        channel = await self.services.channel.get(uid=channel_uid)
        if not channel:
            raise Exception("Channel not found.")
        channel_message = await self.services.channel_message.create(
            channel_uid, user_uid, message, is_final
        )
        channel_message_uid = channel_message["uid"]

        user = await self.services.user.get(uid=user_uid)
        channel["last_message_on"] = now()
        await self.services.channel.save(channel)

        await self.services.socket.broadcast(
            channel_uid,
            {
                "message": channel_message["message"],
                "html": channel_message["html"],
                "user_uid": user_uid,
                "color": user["color"],
                "channel_uid": channel_uid,
                "created_at": channel_message["created_at"],
                "updated_at": None,
                "username": user["username"],
                "uid": channel_message["uid"],
                "user_nick": user["nick"],
                "is_final": is_final,
            },
        )
        await self.app.create_task(
            self.services.notification.create_channel_message(channel_message_uid)
        )

        return channel_message
