<!DOCTYPE html>
<html>
<head>
  <script src="face-api.js"></script>
  <script src="commons.js"></script>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</head>
<body>
  <div id="navbar"></div>
  <div class="center-content page-container">
    <div class="progress" id="loader">
      <div class="indeterminate"></div>
    </div>
    <div style="position: relative" class="margin">
      <img id="inputImg" src="" style="max-width: 800px;" />
      <canvas id="overlay" />
    </div>
    <div class="row side-by-side">
      <div id="selectList"></div>
      <div class="row">
        <label for="imgUrlInput">Get image from URL:</label>
        <input id="imgUrlInput" type="text" class="bold">
      </div>
      <button
        class="waves-effect waves-light btn"
        onclick="loadImageFromUrl()"
      >
        Ok
      </button>
    </div>
    <div class="row">
      <div class="row side-by-side">
        <div class="row">
          <label for="minFaceSize">Minimum Face Size:</label>
          <input disabled value="40" id="minFaceSize" type="text" class="bold">
        </div>
        <button
          class="waves-effect waves-light btn"
          onclick="onDecreaseMinFaceSize()"
        >
          <i class="material-icons left">-</i>
        </button>
        <button
          class="waves-effect waves-light btn"
          onclick="onIncreaseMinFaceSize()"
        >
          <i class="material-icons left">+</i>
        </button>
      </div>
      <div class="row side-by-side">
        <div class="row">
          <label for="minConfidence">Min Confidence:</label>
          <input disabled value="0.7" id="minConfidence" type="text" class="bold">
        </div>
        <button
          class="waves-effect waves-light btn button-sm"
          onclick="onDecreaseMinConfidence()"
        >
          <i class="material-icons left">-</i>
        </button>
        <button
          class="waves-effect waves-light btn button-sm"
          onclick="onIncreaseMinConfidence()"
        >
          <i class="material-icons left">+</i>
        </button>
      </div>
      <div class="row side-by-side">
        <div class="row">
          <label for="maxDistance">Max Descriptor Distance:</label>
          <input disabled value="0.6" id="maxDistance" type="text" class="bold">
        </div>
        <button
          class="waves-effect waves-light btn button-sm"
          onclick="onDecreaseMaxDistance()"
        >
          <i class="material-icons left">-</i>
        </button>
        <button
          class="waves-effect waves-light btn button-sm"
          onclick="onIncreaseMaxDistance()"
        >
          <i class="material-icons left">+</i>
        </button>
      </div>
    </div>
  </div>

  <script>
    let maxDistance = 0.6
    let minConfidence = 0.7
    let minFaceSize = 40
    let trainDescriptorsByClass = []

    function onIncreaseMinFaceSize() {
      minFaceSize = Math.min(faceapi.round(minFaceSize + 20), 200)
      $('#minFaceSize').val(minFaceSize)
    }

    function onDecreaseMinFaceSize() {
      minFaceSize = Math.max(faceapi.round(minFaceSize - 20), 20)
      $('#minFaceSize').val(minFaceSize)
    }

    function onIncreaseMinConfidence() {
      minConfidence = Math.min(faceapi.round(minConfidence + 0.1), 1.0)
      $('#minConfidence').val(minConfidence)
      updateResults()
    }

    function onDecreaseMinConfidence() {
      minConfidence = Math.max(faceapi.round(minConfidence - 0.1), 0.1)
      $('#minConfidence').val(minConfidence)
      updateResults()
    }

    function onIncreaseMaxDistance() {
      maxDistance = Math.min(faceapi.round(maxDistance + 0.1), 1.0)
      $('#maxDistance').val(maxDistance)
      updateResults()
    }

    function onDecreaseMaxDistance() {
      maxDistance = Math.max(faceapi.round(maxDistance - 0.1), 0.1)
      $('#maxDistance').val(maxDistance)
      updateResults()
    }

    async function loadImageFromUrl(url) {
      const img = await requestExternalImage($('#imgUrlInput').val())
      $('#inputImg').get(0).src = img.src
      updateResults()
    }

    async function updateResults() {
      const inputImgEl = $('#inputImg').get(0)
      const { width, height } = inputImgEl
      const canvas = $('#overlay').get(0)
      canvas.width = width
      canvas.height = height

      const mtcnnParams = {
        minFaceSize
      }

      const fullFaceDescriptions = (await faceapi.allFacesMtcnn(inputImgEl, mtcnnParams))
        .map(fd => fd.forSize(width, height))

      fullFaceDescriptions.forEach(({ detection, landmarks, descriptor }) => {
        faceapi.drawDetection('overlay', [detection], { withScore: false })
        faceapi.drawLandmarks('overlay', landmarks, { lineWidth: 4, color: 'red' })
        const bestMatch = getBestMatch(trainDescriptorsByClass, descriptor)
        const text = `${bestMatch.distance < maxDistance ? bestMatch.className : 'unkown'} (${bestMatch.distance})`
        const { x, y, height: boxHeight } = detection.getBox()
        faceapi.drawText(
          canvas.getContext('2d'),
          x,
          y + boxHeight,
          text,
          Object.assign(faceapi.getDefaultDrawOptions(), { color: 'red', fontSize: 16 })
        )
      })
    }

    async function onSelectionChanged(uri) {
      const imgBuf = await fetchImage(uri)
      $(`#inputImg`).get(0).src = (await faceapi.bufferToImage(imgBuf)).src
      updateResults()
    }

    async function run() {
      await faceapi.loadMtcnnModel('/')
      await faceapi.loadFaceRecognitionModel('/')

      trainDescriptorsByClass = await initTrainDescriptorsByClass(faceapi.recognitionNet, 1)

      $('#loader').hide()
      onSelectionChanged($('#selectList select').val())
    }

    $(document).ready(function() {
      renderNavBar('#navbar', 'mtcnn_face_recognition')
      renderImageSelectList(
        '#selectList',
        async (uri) => {
          await onSelectionChanged(uri)
        },
        'bbt1.jpg'
      )
      run()
    })
  </script>
</body>
</html>