<template>
  <div>

    <log-edit v-if="log !== null" :log="log" :validation-errors="validationErrors">
      <div class="buttons">
        <button type="button" class="button is-primary" @click="save">Save Log</button>
        <router-link class="button is-secondary" to="/">Cancel</router-link>
      </div>
    </log-edit>

    <div class="buttons">
      <button type="button" class="button is-primary" @click="save">Save Log</button>
      <router-link class="button is-secondary" to="/">Cancel</router-link>
    </div>

  </div>
</template>

<script setup>

  import { computed, onBeforeMount, ref, watch } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import api from "../lib/Api";
  import * as Errors from "../lib/Errors";
  import LogEdit from "./LogEdit";
  import { useLoadResource } from "../lib/useLoadResource";

  const { loadResource } = useLoadResource();
  const route = useRoute();
  const router = useRouter();

  const validationErrors = ref({});
  const log = ref(null);

  const logId = computed(() => route.params.id);

  onBeforeMount(() => {
    loadResource(
        api.getLog(logId.value)
            .then(data => { log.value = data; return data; })
    );
  });

  function save() {
    validationErrors.value = {};
    loadResource(
        api.patchLog(log.value)
            .then(() => router.push('/'))
            .catch(Errors.onlyFor(Errors.ApiValidationError, err => validationErrors.value = err.validationErrors()))
    );
  }

</script>

<style lang="scss" scoped>
</style>