// VARIABLES

const URL_CHECK_ID = 'upload.php';
const ID = "img-ID";
const canva = "canvas";
const idBtnSubmit = 'btnSubmit';btnSubmit = $("#"+idBtnSubmit);


// SCRIPT

$(document).ready(function(){
    $("#form").on("submit",function (event) {
        event.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            //url de la requête
            url: URL_CHECK_ID,
            
            method: 'POST',
            enctype: 'multipart/form-data',
            data: formData,
            cache: false,

            dataType: "json",
            contentType: false,
            processData: false
        })
        .done(function(data){
          console.log(data);
          $("div#div").empty();
          $("div#div").append(data['message']);

          //Affichage de la photo
          $("#img-ID").attr('src',data['src']);
          findFaces();
        })
        
    });
});

// FONCTIONS

async function findFaces() {
  btnSubmit.prop('disabled',false);
  console.log('_findFaces()');
  const model = await blazeface.load();  
  // const img = ID;
  const img = document.getElementById(ID);
  const predictions = await model.estimateFaces(img, false);
  console.log('_findFaces()');
  if (predictions.length > 0) {
      console.log("faces found")
      console.log(predictions);
      document.getElementById("p-status").innerText += predictions.length+" face(s) found!";
      // const canvas =  document.getElementById(canva);
      // canvas.width = img.width;
      // canvas.height = img.height;
      // const ctx = canvas.getContext("2d");
      // ctx.fillStyle = "rgba(250,225,6,0.5)";
      // for (let i = 0; i < predictions.length; i++) 
      // {
      //   const start = predictions[i].topLeft;
      //   const end = predictions[i].bottomRight;
      //   const size = [end[0] - start[0], end[1] - start[1]];
      //   ctx.fillRect(start[0], start[1], size[0], size[1]);
      //   var landmark;
      //   for (let j = 0; j < predictions[i].landmarks.length; j++)
      //   {
      //     landmark = predictions[i].landmarks[j];
      //     ctx.beginPath();
      //     ctx.arc(landmark[0],landmark[1], 1, 0, 2*Math.PI,false);
      //     ctx.fill();
      //     ctx.lineWidth = 1;
      //     ctx.strokeStyle = '#ff0000';
      //     ctx.stroke();
      //   }
      // }
    } 
    else {
      document.getElementById("status").innerText = "No Face(s) Found";
    }
    btnSubmit.prop('disabled',false);
}


