<?php
use yii\helpers\Html;

?>
<div>
  <div class="card">
    <div class="card-header">
      <span class="h3"><?=$this->title?></span>
      <div class="float-right">
					<label for="cameras">Change Camera</label>
					<div class="input-group">
						<?= Html::dropdownlist('cameras', '', [], ['id' => 'camera-select', 'class' => 'form-control d-inline']); ?>
						<div class="input-group-append">
							<?= Html::button('Save Camera', ['class' => 'btn btn-outline-secondary btn-remember']); ?>
						</div>
					</div>
				</div>	
        </div>
    </div>
		<div class="card-body p-0">
    <video id="video" width="640" height="480" autoplay></video>
    <canvas id="canvas" width="640" height="480"></canvas>
    <button id="start-camera-button">Start Camera</button>
				
		</div>
      <div class="card-footer">
      <div class="text-center p-0">
         <?=HTML::Button('<i class="fa fa-camera"></i>', ['id' => 'capture', 'class' => 'btn ben-default action'])?>
      </div>
    </div>
  </div>
</div>
<script>
  // Get the video and canvas elements
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const cameraSelect = document.getElementById('camera-select');
// Get a list of all media devices
navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    // Filter the list to only include video input devices (cameras)
    const cameras = devices.filter(device => device.kind === 'videoinput');

    // Create a select dropdown for the cameras
    const cameraSelect = document.getElementById('camera-select');
    cameras.forEach(camera => {
      const option = document.createElement('option');
      option.value = camera.deviceId;
      option.text = camera.label;
      cameraSelect.appendChild(option);
    });

    // Add an event listener to the start camera button
    document.getElementById('start-camera-button').addEventListener('click', () => {
      // Get the selected camera
      const selectedCameraId = cameraSelect.value;
      const selectedCamera = cameras.find(camera => camera.deviceId === selectedCameraId);

      // Use the selected camera to access the video stream
      navigator.mediaDevices.getUserMedia({ video: { deviceId: selectedCameraId } })
        .then(stream => {
          // Use the stream to access the camera
          const video = document.getElementById('video');
          video.srcObject = stream;
          video.play();
        })
        .catch(error => {
          console.error('Error getting user media:', error);
        });
    });
  })
  .catch(error => {
    console.error('Error enumerating devices:', error);
  });
</script>