

function loading() {
  $('.btn-save').prop("disabled", true);
  // add spinner to button
  $('.btn-save').html(
    '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'
  );
  window.setTimeout(function () {
    $('.btn-save').prop("disabled", false);
    $('.btn-save').html('<i class="fas fa-camera"></i> Take Photo');
  }, 2000);
}


function loading() {
  $('.loading-webcame').removeClass('d-none');
  $('.loading-webcame').html(
    '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Menyiapkan Kamera..<br>Pastikan cahaya cukup<br>Jika tidak respon ulangi kembali'
  );
  window.setTimeout(function () {
    $('.loading-webcame').addClass('d-none');
  }, 5000);
}



const video = document.getElementById("video");
const guide = document.querySelector('.overlay-recognition');
const statusText = document.getElementById("status");
const captureBtn = document.getElementById("capture");

const CENTER = {
  x: 160,
  y: 120
};
const MAX_OFFSET = 60;
const MIN_SIZE = 90;

Promise.all([
  faceapi.nets.tinyFaceDetector.loadFromUri("../template/vendor/webcame/models"),
  faceapi.nets.faceLandmark68Net.loadFromUri("../template/vendor/webcame/models"),
  faceapi.nets.faceRecognitionNet.loadFromUri("../template/vendor/webcame/models"),
]).then(startVideo);

function startVideo() {
  navigator.mediaDevices.getUserMedia({
    video: {
      facingMode: "user",
      width: 320,
      height: 240
    }
  }).then(s => video.srcObject = s);
}

new faceapi.TinyFaceDetectorOptions({
  inputSize: 160,   // PENTING untuk HP low-end
  scoreThreshold: 0.5
});

setInterval(checkFace, 400);

async function checkFace() {
  const detection = await faceapi
    .detectSingleFace(video, new faceapi.TinyFaceDetectorOptions());

  if (!detection) {
    statusText.innerText = "Wajah tidak terdeteksi";
    $(".result-label").addClass("error");
    $(".result-label").removeClass("success");
    guide.style.borderColor = "red";
    captureBtn.disabled = true;
    return;
  }

  const box = detection.box;
  const faceCenterX = box.x + box.width / 2;
  const faceCenterY = box.y + box.height / 2;

  const offset = Math.hypot(
    faceCenterX - CENTER.x,
    faceCenterY - CENTER.y
  );

  if (box.width < MIN_SIZE) {
    statusText.innerText = "Wajah terlalu jauh";
    $(".result-label").addClass("error");
    $(".result-label").removeClass("success");
    guide.style.borderColor = "danger";
    captureBtn.disabled = true;
    return;
  }

  if (offset > MAX_OFFSET) {
    statusText.innerText = "Posisikan wajah di tengah";
    $(".result-label").addClass("error");
    $(".result-label").removeClass("success");
    guide.style.borderColor = "danger";
    captureBtn.disabled = true;
    return;
  }

  statusText.innerText = "Posisi wajah OK";
  $(".result-label").addClass("success");
  $(".result-label").removeClass("error")
  guide.style.borderColor = "white";
  captureBtn.disabled = false;
}


async function capture() {
  $('.btn-save').html(
    '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'
  );
  window.setTimeout(function () {
    $('.btn-save').prop("disabled", false);
    $('.btn-save').html('<i class="fas fa-camera"></i> Take Photo');
  }, 2000);

  const result = await faceapi
    .detectSingleFace(video, new faceapi.TinyFaceDetectorOptions())
    .withFaceLandmarks()
    .withFaceDescriptor();

  if (!result) {
    swal({ title: 'Wajah Gagal diambil!', text: data, icon: 'error', timer: 2500, });
    return;
  }

  const data = {
    descriptor: Array.from(result.descriptor)
  };

  fetch("./module/recognition/sw-proses.php?action=add", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  })
    .then(async res => {
      const text = await res.text();
      try {
        return JSON.parse(text);
      } catch {
        throw new Error("Response bukan JSON: " + text);
      }
    })
    .then(res => {
      swal({
        title: res.status ? "Berhasil" : "Gagal",
        text: res.msg || "Terjadi kesalahan",
        icon: res.status ? "success" : "error",
        timer: 2500,
        buttons: false
      });

      if (res.status == true) {
        setTimeout(() => {
          window.location.href = "./";
        }, 2500);
      }
    })
    .catch(err => {
      swal({
        title: "Error",
        text: err.message,
        icon: "error",
        timer: 2500,
        buttons: false
      });
    });
}


$(document).ready(function () {
  var descriptor = $('.descriptor').html();
  if (descriptor == 'true') {
    swal({
      title: "Konfirmasi Reset",
      text: "Anda yakin ingin mengganti daftar wajah Anda?",
      icon: "warning",
      buttons: ["Batal", "Ya, Reset!"],
      dangerMode: true, // tombol konfirmasi diberi efek merah
    })
      .then((willReset) => {
        if (willReset) {
          $.ajax({
            url: './module/recognition/sw-proses.php?action=reset',
            type: 'POST',
            dataType: 'json', // memastikan data diterima sebagai JSON
            success: function (res) {
              if (res.status) {
                swal({
                  title: "Berhasil!",
                  text: res.msg,
                  icon: "success",
                  timer: 2500,
                  buttons: false
                }).then(() => {
                  window.location.reload();
                });
              } else {
                swal({
                  title: "Gagal!",
                  text: res.msg,
                  icon: "error",
                  timer: 2500,
                  buttons: false
                });
              }
            },
            error: function (xhr, status, error) {
              swal({
                title: "Error!",
                text: "Terjadi kesalahan: " + error,
                icon: "error",
                timer: 2500,
                buttons: false
              });
            }
          });
        }
      });
  }
});
