<!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>Monitor</title>
    <script src="../socket.io/socket.io.js"></script>
    <script src="RTCMultiConnection.min.js"></script>
</head>
<style>
    /* Estilos del botón */
    #startButton {
        background-color: #505163; /* Color verde para el estado activo */
        color: white;
        border: none;
        padding: 4px 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 13px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.3s;
    }

    #startButton:disabled {
        background-color: red; /* Color gris para el estado desactivado */
        cursor: not-allowed;
    }
    .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;
  text-decoration: none;
  border-radius: 5px;
  font-size: 13px;
}
</style>
<body style="font-family: sans-serif;color: white;zoom:80%">
    
    <div style="background-color: #13141a; padding: 0.3em; max-width: 100%; min-height: 212px;" >
    <video style="max-width: 23em;" id="localVideo" autoplay playsinline muted></video>
    
    </div>
     <div style="margin:4px">
        <button style="color:white;border-radius: 4px;" id="startButton">OFF</button>
        <input class="inp" type="text" id="roomId" placeholder="Monitor" value="Monitor"/>
        <a class="fcc-btn" href="/monitor-out1.html" >REFRES</a>
     </div>
     <div style="margin: 8px;display: flex;flex-direction: column;">
    <div>
        <label for="videoDevices">V:</label>
        <select style="background-color: #52586b;color: white;" id="videoDevices"></select>
    </div>

    <div style="margin-left: 0px;">
        <label for="audioDevices">A:</label>
        <select style=" max-width: 10em;background-color: #52586b;color: white;" id="audioDevices"></select>
    </div>
   </div>
    <script>
        const socket = io();
        const connection = new RTCMultiConnection();

        connection.socketURL = '/';

        // Configuración de la sesión para alta calidad de video
        connection.session = {
            video: true,
            audio: true,
            oneway: true
        };
        connection.mediaConstraints = {
           video: {
           width: { ideal: 1280, min: 1280 },  // Ajusta el ancho de video
            height: { ideal: 720, min: 720 }, // Ajusta la altura de video
            frameRate: { ideal: 30 } // Ajusta la tasa de frames por segundo
           }
        };
        /*
        // Configura las opciones de codec para WebRTC
        connection.sdpConstraints.mandatory = {
        OfferToReceiveAudio: true,
        OfferToReceiveVideo: true
            }; */

       

        let currentStream = null;

        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);
            }
        }

        async function setupMediaStream() {
            const videoDeviceId = document.getElementById('videoDevices').value;
            const audioDeviceId = document.getElementById('audioDevices').value;

            console.log('Seleccionado videoDeviceId:', videoDeviceId);
            console.log('Seleccionado audioDeviceId:', audioDeviceId);

            const constraints = {
                video: { 
                    deviceId:videoDeviceId ?  { exact: videoDeviceId }  : undefined,
            width: { min: 1280 },  // Ajusta el ancho de video
            height: { min: 720 }, // Ajusta la altura de video
            frameRate: { ideal: 30 } // Ajusta la tasa de frames por segundo
        },
                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);
                console.log('Stream obtenido:', stream);
                
                currentStream = stream; // Guardar el stream actual
                connection.addStream(stream);
                document.getElementById('localVideo').srcObject = stream;
            } catch (error) {
                console.error('Error al obtener el stream de medios:', error);
            }
        }

        document.getElementById('startButton').addEventListener('click', () => {
            const roomId = document.getElementById('roomId').value.trim();
            if (roomId) {
                 // Desactiva el botón de inicio para evitar múltiples clics
               const startButton = document.getElementById('startButton');
                startButton.disabled = true;
                startButton.textContent = 'ON >>';
                //startButton.style.display = 'none';
                //const audioDevices = document.getElementById('audioDevices');
                //audioDevices.disabled = true;
                //audioDevices.textContent = 'ON >>';
                //audioDevices.style.display = 'none';

                setupMediaStream().then(() => {
                    connection.open(roomId);
                }).catch(error => {
                    console.error('Error al configurar el stream de medios:', error);
                    // Reactiva el botón en caso de 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);

        window.onload = () => {
            getMediaDevices();
        };

        // Solicitar permisos para acceso a cámara y micrófono
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then(stream => {
                // Permiso concedido
                stream.getTracks().forEach(track => track.stop());
            })
            .catch(err => {
                // Permiso denegado o error
                console.error('Error al solicitar permisos de medios:', err);
                alert('Por favor, concede permisos de cámara y micrófono.');
            });
            // Intercepta el evento cuando un nuevo video se agrega
            connection.onstream = function(event) {
                // Asegúrate de obtener el elemento de video recién creado
             let videoElement = document.getElementById(event.stream.id);
                if (videoElement) {
              // Personaliza el elemento de video según sea necesario
                  videoElement.setAttribute('controls', 'true');
                     videoElement.setAttribute('volume', '0');
        
                // Por ejemplo, si deseas ocultar el elemento:
                 videoElement.style.display = 'none';
            }
            };
            // Reconectar automáticamente en caso de pérdida de conexión
        connection.onConnectionLost = () => {
            console.warn('Conexión perdida, intentando reconectar...');
            setTimeout(() => {
                const roomId = document.getElementById('roomId').value.trim();
                if (roomId) {
                    connection.open(roomId);
                }
            }, 5000); // Intenta reconectar después de 5 segundos
        };

        connection.onReconnected = () => {
            console.log('Reconectado exitosamente.');
            const startButton = document.getElementById('startButton');
            startButton.disabled = false;
            startButton.textContent = 'Iniciar Transmisión';
        };

        window.onload = () => {
            getMediaDevices();
        };
    </script>
</body>
</html>
