from urllib.parse import urlparse
from typing import Optional
from bovine import BovineClient


class MastodonQuoter:
    def __init__(self, client: BovineClient, url: str):
        self.client: BovineClient = client
        self.url: str = url

        self.article = None
        self.author: Optional[str] = None
        self.oembed_html: Optional[str] = None

        self._mention: Optional[dict] = None

    async def collect_information(self):
        self.article = await self.client.proxy_element(self.url)

        self.author = self.article["attributedTo"]

        oembed_result = await self.client.client.get(self.determine_oembed_url())
        self.oembed_html = (await oembed_result.json())["html"]

    def determine_oembed_url(self):
        remote_host = urlparse(self.url).netloc

        return f"https://{remote_host}/api/oembed?url={self.url}"

    async def mention(self):
        if self._mention:
            return self._mention

        if not self.author:
            await self.collect_information()

        object_factory = self.client.object_factory
        self._mention = (
            await object_factory.mention_for_actor_uri(self.author)
        ).build()

        return self._mention

    async def notification(self, post_url):
        mention = await self.mention()
        object_factory = self.client.object_factory

        event = object_factory.event(
            to={self.author},
            name="You have been quoted",
            summary=f"""Your post {self.url} has been quoted on
{post_url}.

This Event was generated by longhorn
(https://codeberg.org/helge/longhorn) to inform you.
""",
            url=post_url,
            tag=[mention],
        )

        return event.build()

    def object_link(self):
        media_type = (
            'application/ld+json; profile="https://www.w3.org/ns/activitystreams"'
        )
        return {
            "type": "Link",
            "mediaType": media_type,
            "href": self.article["id"],
            "name": f"RE: {self.url}",
        }
