<script setup>
import { ref, defineProps } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { parseError, hasError, getError} from "@/components/request/HandleGlobalError.vue";
import ShowErrorField from "@/components/global/ShowErrorField.vue";
import PosNotes from "@/components/displays/department/pos/PosNotes.vue";

const props = defineProps({
  user_id: Number,
  readOnly: {
    type: Boolean,
    default: false
  },
});

const uniqueId = () => {
  return Math.random().toString(36).substring(2, 15);
};
const notes = ref(null);
const isLoaded = ref(false);
const isLoading = ref(false);
const uniqueElementId = uniqueId();

const getNotes = async () => {
  isLoading.value = true;
  // Get the notes
  await SessionUser.request(
      '/customer/notes',
      'GET',
      {
        user_id: props.user_id,
      }
  ).then((response) => {
    // Check if the key exists
    try {
      if (response.data.data) {
        notes.value = response.data.data;
        isLoaded.value = true;
      }
    } catch (e) {
      parseError(e, uniqueElementId);
    }
    isLoading.value = false;
  }).catch((error) => {
    parseError(error, uniqueElementId);
    isLoading.value = false;
  });
};

getNotes();
</script>

<template>
  <div>
    <template v-if="!isLoaded && !isLoading">
      <!-- Check if there is an error -->
      <template v-if="hasError(uniqueElementId)">
        <ShowErrorField :error="uniqueElementId" />
      </template>
      <template v-else>
        <p>Unable to load notes, but no error was found.</p>
      </template>
    </template>
    <template v-else-if="isLoading">
      <progress class="progress is-small is-link" max="100">Loading...</progress>
    </template>
    <template v-else-if="props.readOnly">
      <pos-notes
          :notes="notes"
          :isAddFormVisible="false"
          :isOldNotesVisible="true"
          :isLabelVisible="false"
          />
    </template>
    <template v-else>
      <pos-notes
          :notes="notes"
          :isAddFormVisible="true"
          :isOldNotesVisible="true"
          :isLabelVisible="true"
          />
    </template>
  </div>
</template>

<style scoped>

</style>