<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
  },
  reference: {
    type: String,
    required: true
  },
  loadOrder: {
    type: Function,
    required: true
  }
});

// Check if the required props are set
if (props.order_id === null || props.reference === null || props.loadOrder === null) {
  const missingProps = [];
  if (props.order_id === null) {
    missingProps.push("order_id");
  }
  if (props.reference === null) {
    missingProps.push("reference");
  }
  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 reference, this is separate from the props reference, because otherwise we risk loosing changes.
const input = ref(props.reference);

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

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

// 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 reference 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 reference, then return
  if (input.value === props.reference && !options.force) {
    return;
  }
  // Set the reference to the input value
  props.reference = input.value;
  // Save the order
  SessionUser.request('/order', 'PUT', {
    id: props.order_id,
    field: 'reference',
    value: input.value
  }).then((response) => {
    console.log(response);
    // Load the order
    props.loadOrder();
  }).catch((error) => {
    console.error(error);
  });
}

// Sync the reference with the server once every 2 seconds, if the reference has changed.
setInterval(() => {
  if (input.value !== props.reference && 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 shortReference = ref('');

watch(() => props.reference, (value) => {
  generateShortReference();
});

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

generateShortReference();
</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 reference nummer, dette inkluderes i fakturaen og kan bruges til at finde ordren"
          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-text="shortReference"
      ></textarea>
    </div>
  </div>
</template>

<style scoped>

</style>