# This file is part of Gajim.
#
# SPDX-License-Identifier: GPL-3.0-only

# Presence handler

from __future__ import annotations

from typing import Any
from typing import Literal

import time

import nbxmpp
from nbxmpp.namespaces import Namespace
from nbxmpp.protocol import JID
from nbxmpp.structs import PresenceProperties
from nbxmpp.structs import StanzaHandler

from gajim.common import app
from gajim.common import idle
from gajim.common import types
from gajim.common.events import PresenceReceived
from gajim.common.events import ShowChanged
from gajim.common.events import SubscribedPresenceReceived
from gajim.common.events import SubscribePresenceReceived
from gajim.common.events import UnsubscribedPresenceReceived
from gajim.common.i18n import _
from gajim.common.modules.base import BaseModule
from gajim.common.modules.contacts import BareContact
from gajim.common.modules.contacts import ResourceContact
from gajim.common.structs import PresenceData


class Presence(BaseModule):
    _nbxmpp_extends = "BasePresence"
    _nbxmpp_methods = [
        "subscribed",
    ]

    def __init__(self, con: types.Client) -> None:
        BaseModule.__init__(self, con)

        self.handlers = [
            StanzaHandler(
                name="presence",
                callback=self._presence_received,
                typ="available",
                priority=50,
            ),
            StanzaHandler(
                name="presence",
                callback=self._presence_received,
                typ="unavailable",
                priority=50,
            ),
            StanzaHandler(
                name="presence",
                callback=self._subscribe_received,
                typ="subscribe",
                priority=49,
            ),
            StanzaHandler(
                name="presence",
                callback=self._subscribed_received,
                typ="subscribed",
                priority=49,
            ),
            StanzaHandler(
                name="presence",
                callback=self._unsubscribe_received,
                typ="unsubscribe",
                priority=49,
            ),
            StanzaHandler(
                name="presence",
                callback=self._unsubscribed_received,
                typ="unsubscribed",
                priority=49,
            ),
        ]

        self._presence_store: dict[JID, PresenceData] = {}

        # keep the jids we auto added (transports contacts) to not send the
        # SUBSCRIBED event to GUI
        self.automatically_added: set[JID] = set()

        # list of jid to auto-authorize
        self._jids_for_auto_auth: set[JID] = set()

    def _presence_received(
        self,
        _con: types.NBXMPPClient,
        stanza: nbxmpp.protocol.Presence,
        properties: PresenceProperties,
    ) -> None:

        self._log.info("Received from %s", properties.jid)

        if properties.from_muc:
            # MUC occupant presences are already handled in MUC module
            return

        assert properties.jid is not None
        muc = self._client.get_module("MUC").get_muc_data(properties.jid)
        if muc is not None:
            # Presence from the MUC itself, used for MUC avatar
            # handled in VCardAvatars module
            return

        roster_item = self._client.get_module("Roster").get_item(
            properties.jid.new_as_bare()
        )

        if roster_item is None and not properties.is_self_bare:
            # Handle only presence from roster contacts
            self._log.warning("Unknown presence received")
            self._log.warning(stanza)
            return

        presence_data = PresenceData.from_presence(properties)
        self._presence_store[properties.jid] = presence_data

        contact = self._client.get_module("Contacts").get_contact(properties.jid)
        assert isinstance(contact, BareContact | ResourceContact)
        contact.update_presence(presence_data)

        assert properties.type is not None
        assert properties.show is not None
        if properties.is_self_presence and not properties.type.is_unavailable:
            app.ged.raise_event(
                ShowChanged(account=self._account, show=properties.show.value)
            )
            return

        show = properties.show.value
        if properties.type.is_unavailable:
            show = "offline"

        event_attrs: dict[str, Any] = {
            "account": self._account,
            "stanza": stanza,
            "prio": properties.priority,
            "need_add_in_roster": False,
            "popup": False,
            "ptype": properties.type.value,
            "jid": properties.jid.new_as_bare(),
            "resource": properties.jid.resource,
            "id_": properties.id,
            "fjid": str(properties.jid),
            "timestamp": properties.timestamp,
            "avatar_sha": properties.avatar_sha,
            "user_nick": properties.nickname,
            "show": show,
            "new_show": show,
            "old_show": 0,
            "status": properties.status,
            "contact_list": [],
            "contact": None,
        }

        app.ged.raise_event(PresenceReceived(**event_attrs))

    def _subscribe_received(
        self,
        _con: types.NBXMPPClient,
        _stanza: nbxmpp.protocol.Presence,
        properties: PresenceProperties,
    ) -> None:
        assert properties.jid is not None
        jid = properties.jid.new_as_bare()

        is_transport = app.jid_is_transport(str(properties.jid))
        auto_auth = app.settings.get_account_setting(self._account, "autoauth")

        self._log.info(
            "Received Subscribe: %s, transport: %s, auto_auth: %s, user_nick: %s",
            properties.jid,
            is_transport,
            auto_auth,
            properties.nickname,
        )

        if auto_auth or jid in self._jids_for_auto_auth:
            self._log.info("Auto respond with subscribed: %s", jid)
            self.subscribed(jid)
            return

        ignore_unknown_contacts = app.settings.get_account_setting(
            self._account, "ignore_unknown_contacts"
        )
        if ignore_unknown_contacts:
            self._log.info("Contact request ignored due to ignore_unknown_contacts")
            return

        status = properties.status or _("I would like to add you to my roster.")

        app.ged.raise_event(
            SubscribePresenceReceived(
                account=self._account,
                jid=jid,
                status=status,
                user_nick=properties.nickname,
                is_transport=is_transport,
            )
        )

        raise nbxmpp.NodeProcessed

    def _subscribed_received(
        self,
        _con: types.NBXMPPClient,
        _stanza: nbxmpp.protocol.Presence,
        properties: PresenceProperties,
    ) -> None:
        assert properties.jid is not None
        self._log.info("Received Subscribed: %s", properties.jid)
        bare_jid = properties.jid.new_as_bare()
        if bare_jid in self.automatically_added:
            self.automatically_added.discard(bare_jid)
            raise nbxmpp.NodeProcessed

        app.ged.raise_event(
            SubscribedPresenceReceived(account=self._account, jid=properties.jid)
        )
        raise nbxmpp.NodeProcessed

    def _unsubscribe_received(
        self,
        _con: types.NBXMPPClient,
        _stanza: nbxmpp.protocol.Presence,
        properties: PresenceProperties,
    ) -> None:
        self._log.info("Received Unsubscribe: %s", properties.jid)
        raise nbxmpp.NodeProcessed

    def _unsubscribed_received(
        self,
        _con: types.NBXMPPClient,
        _stanza: nbxmpp.protocol.Presence,
        properties: PresenceProperties,
    ) -> None:
        assert properties.jid is not None
        self._log.info("Received Unsubscribed: %s", properties.jid)
        app.ged.raise_event(
            UnsubscribedPresenceReceived(
                account=self._account, jid=properties.jid.new_as_bare()
            )
        )
        raise nbxmpp.NodeProcessed

    def unsubscribed(self, jid: JID) -> None:
        self._log.info("Unsubscribed: %s", jid)
        self._jids_for_auto_auth.discard(jid)
        self._nbxmpp("BasePresence").unsubscribed(jid)

    def unsubscribe(self, jid: JID) -> None:
        self._log.info("Unsubscribe from %s", jid)
        self._jids_for_auto_auth.discard(jid)
        self._nbxmpp("BasePresence").unsubscribe(jid)

    def subscribe(
        self,
        jid: JID,
        msg: str | None = None,
        name: str | None = None,
        groups: list[str] | set[str] | None = None,
        auto_auth: bool = False,
    ) -> None:
        self._log.info("Request Subscription to %s", jid)

        if auto_auth:
            self._jids_for_auto_auth.add(jid)

        self._client.get_module("Roster").set_item(jid, name, groups=groups)
        self._nbxmpp("BasePresence").subscribe(
            jid, status=msg, nick=self._client.get_own_contact().name
        )

    def get_presence(
        self,
        to: str | JID | None = None,
        typ: Literal["probe", "unavailable"] | None = None,
        show: str | None = None,
        status: str | None = None,
        nick: str | None = None,
        caps: bool = True,
        idle_time: bool = False,
    ) -> nbxmpp.Presence:
        if show not in ("chat", "away", "xa", "dnd"):
            # Gajim sometimes passes invalid show values here
            # until this is fixed this is a workaround
            show = None
        presence = nbxmpp.Presence(to=to, typ=typ, show=show, status=status)
        if nick is not None:
            nick_tag = presence.setTag("nick", namespace=Namespace.NICK)
            nick_tag.setData(nick)

        if idle_time and app.is_installed("IDLE") and app.settings.get("autoaway"):
            idle_sec = idle.Monitor.get_idle_sec()
            time_ = time.strftime(
                "%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - idle_sec)
            )

            idle_node = presence.setTag("idle", namespace=Namespace.IDLE)
            idle_node.setAttr("since", time_)

        own_entity_caps = self._client.get_module("Caps").get_own_caps()
        if own_entity_caps is not None and typ != "unavailable":
            presence.setTag(
                "c", namespace=Namespace.CAPS, attrs=own_entity_caps._asdict()
            )

        return presence

    def send_presence(self, *args: Any, **kwargs: Any) -> None:
        if not app.account_is_connected(self._account):
            return
        presence = self.get_presence(*args, **kwargs)
        app.plugin_manager.extension_point("send-presence", self._account, presence)
        self._log.debug("Send presence:\n%s", presence)
        self._client.send_stanza(presence)
