
function listeSnap() {
  $.ajax({
    type: "POST",
    url: $("#cf_url").val()+"/scan/liste_snap",
    data: "id_bu="+$("#id_bu").val(),
    success: function(msg){
      $("#div_liste_snap").html(msg) ;
    }
  });
}

feather.replace();

const controls = document.querySelector('.controls');
const cameraOptions = document.querySelector('.video-options>select');
// const facingOptions = document.querySelector('.facing-options>select');
const video = document.querySelector('video');
const canvas = document.querySelector('canvas');
const screenshotImage = document.querySelector('img');
const buttons = [...controls.querySelectorAll('button')];
let streamStarted = false;

const [play, pause, screenshot] = buttons;
// alert($("#facingMode").val()) ;
const constraints = {
  video: {
    width: {
      min: 1280,
      ideal: 1920,
      max: 2560,
    },
    height: {
      min: 720,
      ideal: 1080,
      max: 1440
    },
    facingMode: $("#facingMode").val()
  }
};

// facingOptions.onchange = () => {
//   var upConstraints = {
//     video: {
//       width: {
//         min: 1280,
//         ideal: 1920,
//         max: 2560,
//       },
//       height: {
//         min: 720,
//         ideal: 1080,
//         max: 1440
//       },
//       facingMode: facingOptions.value
//     }
//   };
//   startStream(upConstraints);
// };


play.onclick = () => {
  if (streamStarted) {
    video.play();
    play.classList.add('d-none');
    pause.classList.remove('d-none');
    return;
  }
  if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
    const updatedConstraints = {
      ...constraints,
      deviceId: {
        exact: cameraOptions.value
      }
    };
    startStream(updatedConstraints);
  }
};





cameraOptions.onchange = () => {
  const updatedConstraints = {
    ...constraints,
    deviceId: {
      exact: cameraOptions.value
    }
  };

  startStream(updatedConstraints);
};



const pauseStream = () => {
  video.pause();
  play.classList.remove('d-none');
  pause.classList.add('d-none');
};

const doScreenshot = () => {
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  canvas.getContext('2d').drawImage(video, 0, 0);
  screenshotImage.src = canvas.toDataURL('image/webp');
  screenshotImage.classList.remove('d-none');
  // alert($("#cf_url").val()+"/scan/sav_snap?id_bu="+$("#id_bu").val()+"&base64="+canvas.toDataURL('image/base64')) ;
  $.ajax({
    type: "POST",
    url: $("#cf_url").val()+"/scan/sav_snap",
    data: "id_bu="+$("#id_bu").val()+"&base64="+encodeURIComponent(canvas.toDataURL('image/base64')),
    success: function(msg){
      listeSnap() ;
      // alert(msg) ;
      // $("#results").html(msg) ;
    }
  });
  // alert(canvas.toDataURL('image/base64')) ;

};

const doChange = () => {
  /*
  updatedConstraints = {
    ...constraints,
    facingMode: "user"
  };
  startStream(updatedConstraints);
  alert("ok") ;
  */
  /*
  const updatedConstraints = {
    ...constraints,
    facingMode: {
      exact: "user"
    }
  };
  */
  //
  // startStream(updatedConstraints);
  // canvas.width = video.videoWidth;
  // canvas.height = video.videoHeight;
  // canvas.getContext('2d').drawImage(video, 0, 0);
  // screenshotImage.src = canvas.toDataURL('image/webp');
  // screenshotImage.classList.remove('d-none');
};

pause.onclick = pauseStream;
screenshot.onclick = doScreenshot;
// change.onclick = doChange;

const startStream = async (constraints) => {
  const stream = await navigator.mediaDevices.getUserMedia(constraints);
  handleStream(stream);
};


const handleStream = (stream) => {
  video.srcObject = stream;
  play.classList.add('d-none');
  pause.classList.remove('d-none');
  screenshot.classList.remove('d-none');
  change.classList.remove('d-none');

};


const getCameraSelection = async () => {
  const devices = await navigator.mediaDevices.enumerateDevices();
  const videoDevices = devices.filter(device => device.kind === 'videoinput');
  const options = videoDevices.map(videoDevice => {
    return `<option value="${videoDevice.deviceId}">${videoDevice.label}</option>`;
  });
  cameraOptions.innerHTML = options.join('');
};

getCameraSelection();

$(document).ready(function(){
  if (streamStarted) {
    video.play();
    play.classList.add('d-none');
    pause.classList.remove('d-none');
    return;
  }
  if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
    const updatedConstraints = {
      ...constraints,
      deviceId: {
        exact: cameraOptions.value
      }
    };
    startStream(updatedConstraints);
  }

  listeSnap() ;

}) ;

/*
$(document).ready(function(){
  var webCamElement = document.getElementById("camera");
  var canvasElement = document.getElementById("canvas");
  const webcam = new Webcam(webCamElement, 'environment', canvasElement, null);
  webcam.start();
  $('#flip').click(function(){
    webcam.flip() ;
  });
  $('#change_device').click(function(){
    webcam.selectedDeviceId($("#videoSource").val());
    webcam.selectCamera();
  });
  $('#checker').click(function(){
      var picture = webcam.snap();
      $.ajax({
    type: "POST",
    url: $("#cf_url").val()+"/scan/sav_snap",
    data: "id_bu="+$("#id_bu").val()+"&base64="+encodeURIComponent(picture),
    success: function(msg){
        $("#results").html(msg) ;
    }
});
  });
});
*/
