#!/usr/bin/env python3

# Libervia: an XMPP client
# Copyright (C) 2009-2026 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 twisted.words.xish import domish

from libervia.backend.plugins.plugin_xep_0339 import NS_JINGLE_RTP_SSMA, XEP_0339
from libervia.backend.tools.xml_tools import parse


class TestXEP0339:
    def test_parse_sdp(self, host):
        """'ssrc' and 'ssrc-group' attributes in SDP are correctly parsed"""
        xep_0339 = XEP_0339(host)

        call_data = {}
        metadata = {}
        media_type = "video"
        application_data = {}
        transport_data = {}

        # SDP: a=ssrc:123 label:stream_label
        attribute = "ssrc"
        parts = ["123", "label:stream_label"]

        xep_0339._parse_sdp_a_trigger(
            attribute,
            parts,
            call_data,
            metadata,
            media_type,
            application_data,
            transport_data,
        )

        assert application_data == {"ssrc": {123: {"label": "stream_label"}}}

        application_data = {}

        # SDP: a=ssrc-group:FID 123 456
        attribute = "ssrc-group"
        parts = ["FID", "123", "456"]

        xep_0339._parse_sdp_a_trigger(
            attribute,
            parts,
            call_data,
            metadata,
            media_type,
            application_data,
            transport_data,
        )

        assert application_data == {"ssrc-group": {"FID": [123, 456]}}

    def test_generate_sdp(self, host):
        """'ssrc' and 'ssrc-group' attributes in SDP are correctly generated"""
        xep_0339 = XEP_0339(host)

        media_data = {
            "ssrc": {123: {"label": "stream_label"}},
            "ssrc-group": {"FID": [123, 456]},
        }
        sdp_lines = []

        xep_0339._generate_sdp_content_trigger(
            {}, True, 1, {}, sdp_lines, {}, "", media_data, "video"
        )

        assert sdp_lines == ["a=ssrc:123 label:stream_label", "a=ssrc-group:FID 123 456"]

    def test_parse_description(self, host):
        """'<source>' and '<ssrc-group>' elements are correctly parsed"""
        xep_0339 = XEP_0339(host)

        media_data = {}
        raw_xml = """
        <description xmlns='urn:xmpp:jingle:apps:rtp:1' media='audio'>
          <source xmlns='urn:xmpp:jingle:apps:rtp:ssma:0' ssrc='1'>
            <parameter name='cname' value='some_name'/>
            <parameter name='msid' value='media'/>
          </source>
          <ssrc-group xmlns='urn:xmpp:jingle:apps:rtp:ssma:0' semantics='FEC'>
            <source ssrc='2'/>
            <source ssrc='3'/>
          </ssrc-group>
        </description>
        """
        desc_elt = parse(raw_xml)

        xep_0339._parse_description_trigger(desc_elt, media_data)

        assert media_data == {
            "msid": "media",
            "ssrc": {
                1: {
                    "cname": "some_name",
                    "msid": "media",
                }
            },
            "ssrc-group": {"FEC": [2, 3]},
        }

    def test_generate_description(self, host):
        """'<source>' and '<ssrc-group>' elements are correctly generated"""
        xep_0339 = XEP_0339(host)

        media_data = {
            "ssrc": {
                1: {
                    "cname": "some_name",
                    "msid": "media",
                }
            },
            "ssrc-group": {"FEC": [2, 3]},
        }
        session = {}
        desc_elt = domish.Element((None, "description"))

        xep_0339._build_description_trigger(desc_elt, media_data, session)

        source_elts = list(desc_elt.elements(NS_JINGLE_RTP_SSMA, "source"))
        assert len(source_elts) == 1
        source_elt = source_elts[0]
        assert source_elt["ssrc"] == "1"
        param_elts = list(source_elt.elements(NS_JINGLE_RTP_SSMA, "parameter"))
        assert len(param_elts) == 2
        assert param_elts[0]["name"] == "cname"
        assert param_elts[0]["value"] == "some_name"
        assert param_elts[1]["name"] == "msid"
        assert param_elts[1]["value"] == "media"

        ssrc_group_elts = list(desc_elt.elements(NS_JINGLE_RTP_SSMA, "ssrc-group"))
        assert len(ssrc_group_elts) == 1
        ssrc_group_elt = ssrc_group_elts[0]
        assert ssrc_group_elt["semantics"] == "FEC"
        ssrc_ids = [
            int(source_elt["ssrc"])
            for source_elt in ssrc_group_elt.elements(NS_JINGLE_RTP_SSMA, "source")
        ]
        assert ssrc_ids == [2, 3]
