from snek.model.channel_message import ChannelMessageModel
from snek.system.model import BaseModel, ModelField


class ChannelModel(BaseModel):
    label = ModelField(name="label", required=True, kind=str)
    description = ModelField(name="description", required=False, kind=str)
    tag = ModelField(name="tag", required=False, kind=str)
    created_by_uid = ModelField(name="created_by_uid", required=True, kind=str)
    is_private = ModelField(name="is_private", required=True, kind=bool, value=False)
    is_listed = ModelField(name="is_listed", required=True, kind=bool, value=True)
    index = ModelField(name="index", required=True, kind=int, value=1000)
    last_message_on = ModelField(name="last_message_on", required=False, kind=str)

    async def get_last_message(self) -> ChannelMessageModel:
        try:
            async for model in self.app.services.channel_message.query(
                "SELECT uid FROM channel_message WHERE channel_uid=:channel_uid ORDER BY created_at DESC LIMIT 1",
                {"channel_uid": self["uid"]},
            ):

                return await self.app.services.channel_message.get(uid=model["uid"])
        except:
            pass
        return None

    async def get_members(self):
        return await self.app.services.channel_member.find(
            channel_uid=self["uid"], deleted_at=None, is_banned=False
        )
