/*
 * Copyright (c) 2025 Ventum Consulting GmbH
 */


import { waitOnElement } from "@ventum-digital/wait-on";
import { getUrlFactory, pluginFetch } from "@ventum-digital/plugin-fetch";

/**
 * This is a simple example of how to use the waitOnElement function to wait for an element
 * to be present in the DOM and then modify it by appending a message,
 * which is fetched from the server using the pluginFetch function.
 *
 * This snippet adds a message to the view identity page (e.g.: http://localhost:8080/83/define/identity/identity.jsf?id=ac1b2001920e162081920f1a394603b9)
 */
document.addEventListener('DOMContentLoaded', async () => {
  const divSelector = "#bodyDivTitle";

  const getUrl = getUrlFactory("__pluginName__");

  /**
   * Fetches an example message.
   *
   * This asynchronous function makes a call to the plugin using the `pluginFetch` utility.
   * It retrieves a message from the API response or returns an error message if the fetch fails.
   *
   * @function
   * @async
   * @returns A promise that resolves to the example message retrieved from the API.
   *                            If the fetch fails, the returned promise resolves to a default error message.
   */
  const getExampleMessage = async (): Promise<string> => {
    try {
      const response = await pluginFetch(getUrl("getExampleMessage"), {});

      return response.message;
    } catch (error) {
      console.error("Error fetching data:", error);
    }

    return "Error: Could not fetch the message";
  }


  waitOnElement(divSelector, async (element) => {

    // Find "ui-outputpanel ui-widget"
    const querySelector = "#editForm\\:attributeContentA4J";
    const classElement  = document.querySelector(querySelector);

    // Append the message element if the class element is found
    if (classElement) {
      const messageElement = document.createElement("h3");
      messageElement.innerText = await getExampleMessage();

      // Add as the first child
      classElement.prepend(messageElement);
    }
  });
});