<template>
  <div>
    <form action="." method="POST" enctype="multipart/form-data" @submit.prevent="processForm">
      <input id="file" type="file" name="file">
      <input type="submit" value="Submit">
    </form>
    <div id="content"></div>
  </div>
</template>

<style>
  .court {
    background-color: #55acee;
  }
  .date_and_place {
    background-color: yellow;
  }
</style>

<script>
// @ is an alias to /src

export default {
  name: 'Upload',

  methods: {
    processForm: function () {
      const formData = new FormData();
      formData.append("file", document.getElementById("file").files[0]);
      fetch("http://localhost:5000/validator", {method: "POST", body: formData})
      .then(response => response.json())
      .then(result => {
        console.log(Object.entries(result.checks));
        const passed = Object.entries(result.checks).filter(([, val]) => {return val !== false}).map(([key, val]) => [val, key]).sort();
        console.log(passed);

        const content = document.getElementById("content");
        let i = 0;
        for (const detection of passed) {
          const span1 = document.createElement("span");
          span1.innerText = result.parsed_content.slice(i,detection[0][0]);
          content.appendChild(span1);

          const titles = {
            "court": "Označení soudu",
            "date_and_place": "Datum a čas sepsání",
          };

          const span2 = document.createElement("span");
          span2.innerText = result.parsed_content.slice(detection[0][0], detection[0][1]);
          span2.classList.add(detection[1]);
          span2.title = titles[detection[1]];
          content.appendChild(span2);
          i = detection[0][1];
        }
        const span = document.createElement("span");
        span.innerText = result.parsed_content.slice(i);
        content.appendChild(span);
      })
      .catch(err => {
        console.error(err); //TODO
      })
    },
  },
}
</script>
