const videoElement = document.getElementsByClassName('input_video')[0];
const canvasElement = document.getElementsByClassName('output_canvas')[0];
const canvasCtx = canvasElement.getContext('2d');

function getTask() {
  const result = Math.floor(Math.random() * 10);
  const op1 = Math.floor(Math.random() * result);
  const op2 = result - op1;
  return {
    op1,
    op2,
    result,
  };
}
function showTask(task) {
  document.getElementById('task').innerText = `${task.op1} + ${task.op2} = ?`;
}
function getUserResult(multiHandLandmarks) {
  console.log(JSON.stringify(multiHandLandmarks));
  const ref = 5;

  const thumb = 4;
  const index = 8;
  const middle = 12;
  const ring = 16;
  const pinki = 20;
  const fingers = [thumb, index, middle, ring, pinki];

  let value = 0;
  multiHandLandmarks.forEach((handLandmark) => {
    const refY = handLandmark[ref].y;
    if (handLandmark[thumb].y > refY) {
      value++;
    }
    fingers.forEach((finger) => {
      if (handLandmark[finger].y < refY) {
        value++;
      }
    });
  });
  console.log(value);
  return value;
}

function showUserHands(results) {
  canvasCtx.save();
  canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);

  canvasCtx.drawImage(
    results.image,
    0,
    0,
    canvasElement.width,
    canvasElement.height
  );

  if (results.multiHandLandmarks) {
    for (const landmarks of results.multiHandLandmarks) {
      drawConnectors(canvasCtx, landmarks, HAND_CONNECTIONS, {
        color: '#00FF00',
        lineWidth: 5,
      });
      drawLandmarks(canvasCtx, landmarks, { color: '#FF0000', lineWidth: 2 });
    }
  }
  canvasCtx.restore();
}

let task = getTask();
showTask(task);

function onResults(results) {
  const userResult = getUserResult(results.multiHandWorldLandmarks);
  if (userResult === task.result) {
    alert('Congratilations! You are right!');
    task = getTask();
    showTask(task);
  }
  showUserHands(results);
}

const hands = new Hands({
  locateFile: (file) => {
    return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;
  },
});

hands.setOptions({
  maxNumHands: 2,
  modelComplexity: 1,
  minDetectionConfidence: 0.5,
  minTrackingConfidence: 0.5,
});
hands.onResults(onResults);
const camera = new Camera(videoElement, {
  onFrame: async () => {
    await hands.send({ image: videoElement });
  },
  width: 1280,
  height: 720,
});
camera.start();
