<script setup>
import {ref, defineProps, watch, nextTick} from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const props = defineProps({
  order_id: {
    type: Number,
    required: true
  },
  note: {
    type: String,
    required: true
  },
  loadOrder: {
    type: Function,
    required: true
  }
});

// Check if the required props are set
if (props.order_id === null || props.note === null || props.loadOrder === null) {
  const missingProps = [];
  if (props.order_id === null) {
    missingProps.push("order_id");
  }
  if (props.note === null) {
    missingProps.push("note");
  }
  if (props.loadOrder === null) {
    missingProps.push("loadOrder");
  }
  throw new Error("The required props are not set: " + missingProps.join(", "));
}
// Random unique element id
const uniqueId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

// Define the input note, this is separate from the props note, because otherwise we risk loosing changes.
const input = ref(props.note);

// When the props note changes, then update the input note (If the input note is empty)
watch(() => props.note, (value) => {
  if (input.value === "") {
    input.value = value;
  }
});

const isSaved = () => {
  return input.value === props.note;
}

// Define the input changed function
const inputChanged = () => {}

// Define the lost focus function
const lostFocus = () => {
  isEditing.value = false;
  saveChanges({force: true});
}

// Save the last time the note was synced, this is used to prevent spamming the server with requests.
const lastSync = ref(new Date().getTime());

// Define the save changes function
const saveChanges = (options = {}) => {
  // If the input value is the same as the note, then return
  if (input.value === props.note && !options.force) {
    return;
  }
  // Set the note to the input value
  props.note = input.value;
  // Save the order
  SessionUser.request('/order', 'PUT', {
    id: props.order_id,
    field: 'notes',
    value: input.value
  }).then((response) => {
    console.log(response);
    // Load the order
    props.loadOrder();
  }).catch((error) => {
    console.error(error);
  });
}

// Sync the note with the server once every 2 seconds, if the note has changed.
setInterval(() => {
  if (input.value !== props.note && new Date().getTime() - lastSync.value > 2000) {
    lastSync.value = new Date().getTime();
    saveChanges();
  } else {
  }
}, 1000);

const isEditing = ref(false);

const onFieldClicked = () => {
  isEditing.value = true;
  // Wait for the next tick, then focus on the textarea
  nextTick(() => {
    focusOnTextarea();
  });
}

const focusOnTextarea = () => {
  const textarea = document.getElementById(uniqueId + '-textarea');
  if (textarea) {
    textarea.focus();
  }
}

const getRows = () => {
  return Math.max(input.value.split("\n").length, 1);
}

const shortNote = ref('');

watch(() => props.note, (value) => {
  shortNote.value = generateShortNote();
});

const generateShortNote = () => {
  let shownNote = '';
  if (input.value.length > 20 || input.value.split("\n").length > 1) {
    // Get the first line, and add ...
    shownNote = input.value.split("\n")[0].substring(0, 20) + '...';
  } else {
    shownNote = input.value;
  }
  shortNote.value = shownNote;
  return shownNote;
}

generateShortNote();
</script>

<template>
  <div class="field" @click="onFieldClicked()">
    <div class="control" :class="{'is-loading': !isSaved()}">
      <textarea
          v-if="isEditing"
          class="textarea"
          :style="{'height': isEditing ? 'auto' : '2.25em', 'resize': isEditing ? 'vertical' : 'none', 'overflow': 'hidden', 'padding': '0.5em'}"
          :readonly="!isEditing"
          :rows="isEditing ? getRows() : 1"
          placeholder="Ordre note, denne bliver inkluderet i fakturaen"
          v-model="input"
          @input="inputChanged"
          @blur="lostFocus()"
          :id="uniqueId + '-textarea'"
      ></textarea>
      <textarea
          class="textarea"
          :style="{'height': '2.25em', 'resize': 'none', 'overflow': 'hidden', 'padding': '0.5em'}"
          :readonly="true"
          :rows="1"
          v-if="!isEditing"
          v-model="shortNote"
          placeholder="Ordre note, denne bliver inkluderet i fakturaen"
      ></textarea>
    </div>
  </div>
</template>

<style scoped>

</style>