<script>
import { ref } from "vue";
import { authenticatedRequest } from "@/components/session/authenticatedRequest.vue";
import { parseError } from "@/components/request/HandleGlobalError.vue";
import Swal from "sweetalert2";
/**
 * The EditFieldForm object
 * This object is used to edit an objects field
 */
export const EditFieldForm = {
  /**
   * The object
   */
  object: ref(0),
  /**
   * The field
   */
  field: ref(''),
  /**
   * The value
   */
  value: ref(''),
  /**
   * The edit field function
   * @returns {Promise<void>}
   */
  editFormField: async (endpoint, objectId, field, value) => {
    return await authenticatedRequest(endpoint, "PUT", {
      id: objectId,
      field: field,
      value: value
    })
        .then(
            (response) => {
              // Success
            }
        )
        .catch(
            (error) => {
              parseError(error, 'universalEditField');
            }
        );
  },
  showEditFieldForm: async (endpoint, objectId, field, value, displayName = null, functionAfter = null) => {
    // If the display name is not defined, use the field name
    if (displayName === null) {
      displayName = field;
    }
    // Set the object
    EditFieldForm.object.value = objectId;
    // Set the field
    EditFieldForm.field.value = field;
    // Show the edit field form
    return await Swal.fire({
      title: 'Edit ' + displayName,
      html: `
        <input type="text" class="swal2-input" id="editField" value="${value}">
      `,
      showCancelButton: true,
      confirmButtonText: 'Save',
      cancelButtonText: 'Cancel',
      allowOutsideClick: false,
      allowEscapeKey: false,
      allowEnterKey: false
    }).then((result) => {
      if (result.isConfirmed) {
        // Set the value
        EditFieldForm.value.value = document.getElementById('editField').value;
        // Edit the field
        EditFieldForm.editFormField(endpoint, objectId, field, EditFieldForm.value.value);
        // If a function after is defined, run it
        if (functionAfter !== null && functionAfter !== undefined) {
          functionAfter();
        }
      }
    });
  }

};
</script>