from collections.abc import AsyncIterator

from slixmpp.exceptions import XMPPError

from slidge.contact import LegacyContact, LegacyRoster
from slidge.util.types import Avatar, XMPPMessage

from .session import Session


class Roster(LegacyRoster["Contact"]):
    async def fill(self) -> AsyncIterator["Contact"]:
        for i in "111", "222":
            yield await self.by_legacy_id(i)


class Contact(LegacyContact):
    session: "Session"

    @property
    def super_duper_id(self) -> int:
        try:
            return int(self.legacy_id)
        except ValueError:
            raise XMPPError(
                "bad-request", "This is not a valid username for this fake network"
            )

    async def update_info(self) -> None:
        profile = await self.session.legacy_client.get_profile(self.super_duper_id)
        self.name = profile.nickname
        self.set_vcard(full_name=profile.full_name)
        await self.set_avatar(
            Avatar(path=profile.avatar, unique_id=profile.avatar_unique_id)
        )
        if self.legacy_id != "666":
            self.is_friend = True
        self.online()

    async def on_message(self, message: XMPPMessage) -> str | None:
        if message.body:
            sent = await self.session.legacy_client.send_direct_msg(
                message.body, self.super_duper_id
            )
            return sent.id
        return None
