from snek.system.view import BaseView


class ThreadsView(BaseView):

    async def get(self):
        threads = []
        user = await self.services.user.get(uid=self.session.get("uid"))
        async for channel_member in user.get_channel_members():
            thread = {}
            channel = await self.services.channel.get(uid=channel_member["channel_uid"])
            last_message = await channel.get_last_message()
            if not last_message:
                continue

            thread["uid"] = channel["uid"]
            thread["name"] = await channel_member.get_name()
            thread["new_count"] = channel_member["new_count"]
            thread["last_message_on"] = channel["last_message_on"]
            thread["created_at"] = thread["last_message_on"]

            thread["name_color"] = "#f05a28"
            thread["last_message_text"] = last_message["message"]
            thread["last_message_user_uid"] = last_message["user_uid"]
            user_last_message = await self.app.services.user.get(
                uid=last_message["user_uid"]
            )
            if channel["tag"] == "dm":
                thread["name_color"] = user_last_message["color"]
            thread["last_message_user_color"] = user_last_message["color"]
            threads.append(thread)

        threads.sort(key=lambda x: x["last_message_on"] or "", reverse=True)

        return await self.render_template(
            "threads.html", {"threads": threads, "user": user}
        )
