<!DOCTYPE html>
<html lang="en" style="background-color: #272a33;">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Emisor</title>
    <script src="../socket.io/socket.io.js"></script>
    <script src="RTCMultiConnection.min.js"></script>
</head>
<style>
    /* Estilos básicos */
    body {
        font-family: sans-serif;
        color: white;
        zoom: 80%;
    }

    #startButton {
        background-color: #505163;
        color: white;
        border: none;
        padding: 4px 20px;
        font-size: 13px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.3s;
    }

    #startButton:disabled {
        background-color: red;
        cursor: not-allowed;
    }

    #localVideo {
        max-width: 23em;
    }

    .inp {
        background-color: #52586b;
        color: white;
        height: 24px;
        font-size: 14px;
        width: 100px;
        border: none;
        border-radius: 5px;
        padding: 0px 9px;
        display: none;
    }

    .fcc-btn {
        background-color: #55535e;
        color: white;
        padding: 4px 20px;
        font-size: 13px;
        border-radius: 5px;
        text-decoration: none
    }

    select {
        background-color: #52586b;
        color: white;
        border-radius: 5px;
    }
</style>
<body>
    <div style="background-color: #13141a; padding: 0.3em;">
        <video id="localVideo" autoplay playsinline muted></video>
    </div>

    <div style="margin:4px">
        <button id="startButton">OFF</button>
        <a class="fcc-btn" href="/monitor-out1.html" >REFRES</a>
        <input class="inp" type="text" id="roomId" placeholder="Room ID" value="Monitor" />
    </div>

    <div style="margin: 8px; display: flex; flex-direction: column;">
        <div>
            <label for="videoDevices">V:</label>
            <select style="max-width: 10em;" id="videoDevices"></select>
        </div>
        <div>
            <label for="audioDevices">A:</label>
            <select style="max-width: 10em;" id="audioDevices"></select>
        </div>
    </div>

    <script>
        const socket = io();
        const connection = new RTCMultiConnection();

        connection.socketURL = '/'; // La URL del servidor de socket.io

        connection.session = {
            video: true,
            audio: true,
            oneway: true // Permitir solo que el emisor transmita
        };
        
        let currentStream = null;

        // Obtener dispositivos de medios (cámara y micrófono) y cargarlos en los selectores
        async function getMediaDevices() {
            const videoSelect = document.getElementById('videoDevices');
            const audioSelect = document.getElementById('audioDevices');

            try {
                const devices = await navigator.mediaDevices.enumerateDevices();

                videoSelect.innerHTML = '';
                audioSelect.innerHTML = '';

                devices.forEach(device => {
                    const option = document.createElement('option');
                    option.value = device.deviceId;
                    option.text = device.label || (device.kind === 'videoinput' ? 'Cámara ' : 'Micrófono ') + (videoSelect.length + 1);

                    if (device.kind === 'videoinput') {
                        videoSelect.appendChild(option);
                    } else if (device.kind === 'audioinput') {
                        audioSelect.appendChild(option);
                    }
                });
            } catch (error) {
                console.error('Error al enumerar dispositivos de medios:', error);
            }
        }

        // Configurar el flujo de medios basado en los dispositivos seleccionados
        async function setupMediaStream() {
            const videoDeviceId = document.getElementById('videoDevices').value;
            const audioDeviceId = document.getElementById('audioDevices').value;

            const constraints = {
                video: { 
                    deviceId: videoDeviceId ? { exact: videoDeviceId } : undefined,
                    width: { ideal: 1280 },
                    height: { ideal: 720 },
                    frameRate: { ideal: 15 }
                },
                audio: {
                    deviceId: audioDeviceId ? { exact: audioDeviceId } : undefined,
                    noiseSuppression: false,
                    echoCancellation: false,
                    autoGainControl: false
                }
            };

            try {
                // Detener el stream actual si existe
                if (currentStream) {
                    currentStream.getTracks().forEach(track => track.stop());
                }

                const stream = await navigator.mediaDevices.getUserMedia(constraints);
                currentStream = stream;
                connection.addStream(stream);
                document.getElementById('localVideo').srcObject = stream;
            } catch (error) {
                console.error('Error al obtener el stream de medios:', error);
            }
        }

        // Inicializar la conexión cuando el botón de inicio es presionado
        document.getElementById('startButton').addEventListener('click', () => {
            const roomId = document.getElementById('roomId').value.trim();

            if (roomId) {
                const startButton = document.getElementById('startButton');
                startButton.disabled = true;
                startButton.textContent = 'ON >>';

                // Solo cuando el usuario presiona el botón "Start" se obtiene el flujo de medios
                setupMediaStream().then(() => {
                    connection.open(roomId); // Abrir la conexión con el Room ID
                }).catch(error => {
                    console.error('Error al configurar el stream de medios:', error);
                    startButton.disabled = false;
                    startButton.textContent = 'Iniciar';
                });
            } else {
                alert('Por favor, ingrese un Room ID válido.');
            }
        });

        // Escuchar cambios en los selectores de dispositivos y actualizar el stream
        document.getElementById('videoDevices').addEventListener('change', setupMediaStream);
        document.getElementById('audioDevices').addEventListener('change', setupMediaStream);

        // Cargar dispositivos de medios al cargar la página, pero sin obtener los flujos
        window.onload = () => {
            getMediaDevices();
        };

        // Solicitar permisos para acceso a cámara y micrófono solo cuando sea necesario
        // Mover esta parte al evento de "Start"

           // Manejar eventos de conexión y transmisión de medios
        connection.onstream = function(event) {
            const videoElement = document.getElementById(event.stream.id);
            if (videoElement) {
                videoElement.setAttribute('controls', 'true');
                videoElement.setAttribute('volume', '0');
                videoElement.style.display = 'none'; // Ocultar video si no es necesario
            }
        };
    </script>
</body>
</html>
