package com.foxx.androidcast.network;

/*********************************************************************
 * UdpCastTransportBackwardCompatTest.java
 * Created at: Mon 18 May 2026 14:25:02 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class UdpCastTransportBackwardCompatTest
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 60 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	65b83ba338c7bc50f8926e3b4cb8be8c454ff6caf93e1bf0410b06a0a6da31a7
**********************************************************************/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import com.foxx.androidcast.CastConfig;
import com.foxx.androidcast.CastSettings;
import com.foxx.androidcast.network.transport.StreamProtectionMode;

import org.junit.Test;

public class UdpCastTransportBackwardCompatTest {
    @Test
    public void create_startsWithProtectionOff() throws Exception {
        UdpCastTransport udp = new UdpCastTransport();
        CastTransportFactory.applyUdpProtectionDeferred(udp);
        assertEquals(StreamProtectionMode.NONE, udp.getLossStats().protectionMode);
    }

    @Test
    public void foreignFecShard_isIgnoredWithoutNack() throws Exception {
        int port = 38000 + (int) (System.nanoTime() % 2000);
        UdpCastTransport receiver = new UdpCastTransport();
        UdpCastTransport sender = new UdpCastTransport();
        try {
            receiver.prepareListen(port);
            sender.connect("127.0.0.1", port);
            assertEquals(StreamProtectionMode.NONE, receiver.getLossStats().protectionMode);

            CastSettings fec = new CastSettings();
            fec.setTransport(CastConfig.TRANSPORT_UDP);
            fec.setStreamProtection(CastSettings.StreamProtection.FEC_3_4);
            sender.applyStreamProtection(fec);
            byte[] payload = new byte[] {1, 2, 3, 4, 5, 6, 7, 8};
            sender.send(CastProtocol.MSG_VIDEO_FRAME, payload);

            CastProtocol.Message msg = receiver.receive(1000);
            assertNull(msg);
            assertTrue(receiver.getLossStats().unsupportedProtectionDropped >= 1);
        } finally {
            sender.close();
            receiver.close();
        }
    }

    @Test
    public void negotiatedMismatch_usesPlainUdp() {
        CastSettings.StreamProtection mode = com.foxx.androidcast.network.transport.StreamProtectionNegotiator
                .resolve(CastSettings.StreamProtection.FEC_NACK, CastSettings.StreamProtection.NONE);
        assertEquals(CastSettings.StreamProtection.NONE, mode);
    }
}
