from snek.system.model import BaseModel, ModelField


class ChannelMemberModel(BaseModel):
    label = ModelField(name="label", required=True, kind=str)
    channel_uid = ModelField(name="channel_uid", required=True, kind=str)
    user_uid = ModelField(name="user_uid", required=True, kind=str)
    is_moderator = ModelField(
        name="is_moderator", required=True, kind=bool, value=False
    )
    is_read_only = ModelField(
        name="is_read_only", required=True, kind=bool, value=False
    )
    is_muted = ModelField(name="is_muted", required=True, kind=bool, value=False)
    is_banned = ModelField(name="is_banned", required=True, kind=bool, value=False)
    new_count = ModelField(name="new_count", required=False, kind=int, value=0)

    async def get_user(self):
        return await self.app.services.user.get(uid=self["user_uid"])

    async def get_channel(self):
        return await self.app.services.channel.get(uid=self["channel_uid"])

    async def get_name(self):
        channel = await self.get_channel()
        if channel["tag"] == "dm":
            user = await self.get_other_dm_user()
            return user["nick"]
        return channel["name"] or self["label"]

    async def get_other_dm_user(self):
        channel = await self.get_channel()
        if channel["tag"] != "dm":
            return None

        async for model in self.app.services.channel_member.find(
            channel_uid=channel["uid"]
        ):
            if model["uid"] != self["uid"]:
                return await self.app.services.user.get(uid=model["user_uid"])
        return await self.get_user()
