#!/usr/bin/env python3

# Libervia: an XMPP client
# Copyright (C) 2009-2025 Jérôme Poisson (goffi@goffi.org)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


from unittest.mock import MagicMock, patch

import pytest
from twisted.words.protocols.jabber import jid
from twisted.words.xish import domish

from libervia.backend.core import exceptions
from libervia.backend.memory.sqla_mapping import History
from libervia.backend.models.core import MessageData
from libervia.backend.plugins.plugin_xep_0461 import NS_REPLY, ReplyTo, XEP_0461
from pytest_twisted import ensureDeferred as ed


class TestXEP0461:
    @ed
    async def test_reply_to_from_element(self):
        """<reply> element parsing works."""
        # Test correct case
        element = domish.Element(
            (NS_REPLY, "reply"), attribs={"id": "123", "to": "user@example.com"}
        )
        reply = ReplyTo.from_element(element)
        assert reply.to == jid.JID("user@example.com")
        assert reply.id == "123"
        assert not reply.internal_uid

        # Test child element
        parent = domish.Element((None, "some"))
        child = domish.Element((NS_REPLY, "reply"), attribs={"id": "456"})
        parent.addChild(child)
        reply = ReplyTo.from_element(parent)
        assert reply.id == "456"
        assert reply.to is None

        # Test missing id
        element = domish.Element((NS_REPLY, "reply"))
        with pytest.raises(exceptions.DataError):
            ReplyTo.from_element(element)

        # Test no reply
        element = domish.Element((None, "some"))
        with pytest.raises(exceptions.NotFound):
            ReplyTo.from_element(element)

    @ed
    async def test_reply_to_to_element(self, host, client):
        "<reply> element generation works."
        reply = ReplyTo(id="123", internal_uid=True)
        with pytest.raises(exceptions.DataError):
            reply.to_element()

        reply = ReplyTo(id="123", internal_uid=False)
        elt = reply.to_element()
        assert elt.uri == NS_REPLY
        assert elt.name == "reply"
        assert elt["id"] == "123"
        assert not elt.hasAttribute("to")

        reply = ReplyTo(id="123", to=jid.JID("user@example.com"), internal_uid=False)
        elt = reply.to_element()
        assert elt["to"] == "user@example.com"

    @ed
    async def test_xep_0461_message_received_trigger(self, host, client):
        """post_treat callback is added."""
        xep = XEP_0461(host)
        post_treat = MagicMock()
        xep._message_received_trigger(client, None, post_treat)
        assert post_treat.addCallback.called

    @ed
    async def test_xep_0461_send_message_trigger(self, host, client):
        "post_xml_treatments callback is added."
        xep = XEP_0461(host)
        mess_data = MessageData(extra={"reply": {"id": "123", "internal_uid": False}})
        pre_xml_treatments = MagicMock()
        post_xml_treatments = MagicMock()
        xep._sendMessage_trigger(
            client, mess_data, pre_xml_treatments, post_xml_treatments
        )
        assert post_xml_treatments.addCallback.called
