"""Prüft die Formataushandlung nach dem Wi-Fi-Display-Standard."""

import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from wfd import formats


class FormatTest(unittest.TestCase):

    # So antwortet ein handelsüblicher Fernseher auf M3.
    TYPICAL = "00 00 02 04 0001DEFF 155557FF 00000FFF 00 0000 0000 11 none none"

    def test_parses_capabilities(self):
        caps = formats.parse_video_formats(self.TYPICAL)
        self.assertEqual(1, len(caps))
        self.assertEqual(0x02, caps[0].profile)
        self.assertEqual(0x04, caps[0].level)
        self.assertEqual(0x0001DEFF, caps[0].cea_mask)

    def test_chooses_720p30(self):
        chosen = formats.choose(formats.parse_video_formats(self.TYPICAL))
        self.assertEqual((1280, 720, 30), (chosen.width, chosen.height, chosen.fps))

    def test_respects_height_limit(self):
        caps = formats.parse_video_formats(self.TYPICAL)
        chosen = formats.choose(caps, max_height=480)
        self.assertEqual(480, chosen.height)

    def test_falls_back_to_small_format(self):
        caps = formats.parse_video_formats(
            "00 00 01 02 00000003 00000000 00000000 00 0000 0000 00 none none")
        chosen = formats.choose(caps)
        self.assertEqual((640, 480), (chosen.width, chosen.height))

    def test_no_common_format(self):
        caps = formats.parse_video_formats(
            "00 00 01 02 00000000 00000000 00000000 00 0000 0000 00 none none")
        self.assertIsNone(formats.choose(caps))

    def test_never_picks_interlaced(self):
        # Nur interlaced-Bits gesetzt: 2, 4, 9, 14
        mask = (1 << 2) | (1 << 4) | (1 << 9) | (1 << 14)
        caps = formats.parse_video_formats(
            f"00 00 01 02 {mask:08X} 00000000 00000000 00 0000 0000 00 none none")
        self.assertIsNone(formats.choose(caps))

    def test_selection_announces_exactly_one_format(self):
        selection = formats.build_selection(formats.CEA[5], 0x02, 0x04)
        fields = selection.split()
        self.assertEqual(13, len(fields))
        self.assertEqual(1 << 5, int(fields[4], 16))
        self.assertEqual(1, bin(int(fields[4], 16)).count("1"))
        self.assertEqual(["none", "none"], fields[11:13])

    def test_reads_rtp_port(self):
        self.assertEqual(19000, formats.parse_rtp_port("RTP/AVP/UDP;unicast 19000 0 mode=play"))
        self.assertEqual(0, formats.parse_rtp_port(None))


if __name__ == "__main__":
    unittest.main()
