/**
 * @name eventHandlers
 * @description Object with the event handlers for the SDK events
 * @type {Object}
 */
const eventHandlers = {
  VD_mounted: onSDKMounted,
};

const configObject = {
  sdkDocument: {
    flowType: {
      documents: "ES2_ID",
    },
  },
};

// Document instance and available sdk events
let VDDocument, SdkEvents;

// config setup control , set this true if you want to use the config.json instead configObject
let isConfigByFile = true;

window.onload = initializeElementsValue;

// Initialize elements value
function initializeElementsValue() {
  SdkEvents = window.vdDocument.VDDocument.events;
  addListeners();
}

/**
 * @name handleEvent
 * @description Object with the event handlers for the SDK events. You can check the available events in the documentation here: https://docs.veridas.com/document-sdk/html/v4.2/api/#dispatched-events.
 * @param {Object} e Event object
 * @returns {void}
 */
function handleEvent(e) {
  const handler = eventHandlers[e.type];
  if (handler) {
    handler(e);
  }
}

/**
 * @name addListeners
 * @description Adds the event listeners for the SDK events in the `SdkEvents` array
 */
function addListeners() {
  SdkEvents.forEach((sdkEvent) => {
    addEventListener(sdkEvent, (e) => {
      handleEvent(e);
    });
  });
}

async function onSDKMounted() {
  VDDocument = document.querySelector("vd-document");

  if (isConfigByFile) {
    await VDDocument.initializeSdk("./config.json");
  } else if (configObject) {
    await VDDocument.initializeSdk(configObject);
  } else {
    await VDDocument.initializeSdk();
  }
}
