<template>
  <div class="input-mask">
    <span>Ich bin InputMask.vue</span>
    <form @submit.prevent="addGrade">
      <label>
        Modulkürzel
        <input type="text" placeholder="z.B. 'IWS'" v-model="grade_form_input.kuerzel">
      </label>
      <label>
        Note
        <input type="number" min="1" max="5" placeholder="1.0" step="0.1" v-model="grade_form_input.note">
      </label>
      <label>
        Credits
        <input type="number" min="2" max="30" placeholder="5" v-model="grade_form_input.credits">
      </label>
      <button type="submit">Note Eintragen</button>
    </form>
    <!-- @deleteEntry="deleteGrade"-->
    <List :grades="grades" @deleteGrade="deleteGrade"/>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import List from './List.vue';

const grade_form_input = ref({
  kuerzel: "",
  note: 1.0,
  credits: 5
})
const id = ref(4)
const grades = ref([
  {kuerzel: "IWS", note: 1.0, credits: 5, id: 1},
  {kuerzel: "KRY", note: 2.0, credits: 6, id: 2},
  {kuerzel: "WIF", note: 1.7, credits: 4, id: 3},
])

function addGrade() {
  const is_every_input_set = validateInput();
  if (is_every_input_set) {
    grades.value.push({
      kuerzel: grade_form_input.value.kuerzel,
      note: grade_form_input.value.note,
      credits: grade_form_input.value.credits,
      id: id.value
    })
  }
  // clear inputmask variables
  grade_form_input.value = {kuerzel: "", note: 1.0, credits: 5}
  id.value++
}

function validateInput() {
  const grade_steps = [1.0, 1.3, 1.5, 1.7, 2.0, 2.3, 2.5, 2.7, 3.0, 3.3, 3.5, 3.7, 4.0, 5.0];
  const not_empty = Object.values(grade_form_input.value).every(value => value !== "");
  const valid_grade = grade_steps.includes(parseFloat(grade_form_input.value.note));
  return valid_grade && not_empty ? true : false;
}

function deleteGrade(id) {
  grades.value = grades.value.filter(e => e.id !== id)
}
</script>

<style scoped>

</style>
