from datetime import datetime, timezone

from snek.model.user import UserModel
from snek.system.model import BaseModel, ModelField


class ChannelMessageModel(BaseModel):
    channel_uid = ModelField(name="channel_uid", required=True, kind=str)
    user_uid = ModelField(name="user_uid", required=True, kind=str)
    message = ModelField(name="message", required=True, kind=str)
    html = ModelField(name="html", required=False, kind=str)
    is_final = ModelField(name="is_final", required=True, kind=bool, value=True)

    def get_seconds_since_last_update(self):
        return int(
            (
                datetime.now(timezone.utc) - datetime.fromisoformat(self["updated_at"])
            ).total_seconds()
        )

    async def get_user(self) -> UserModel:
        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"])
