/**
 * @name eventHandlers
 * @description Object with the event handlers for the SDK events. You can check the available events in the documentation here: https://docs.veridas.com/sap-sdk/html/v4.4/api/#dispatched-events.
 * @type {Object}
 */
const eventHandlers = {
  VD_mounted: onSDKMounted,
  VD_restartProcess: handleRestartProcess,
}

const configObject = {
  generic: {
    theme: {
      colorAlertError: "#d63737",
      colorAlertSuccess: "#AEE4C1",
      colorNeutral00: "#ffffff",
      colorNeutral05: "#f2f2f2",
      colorNeutral20: "#cccccc",
      colorNeutral40: "#999999",
      colorPrimaryDark: "#000D44",
      colorPrimaryMain: "#000D44",
      colorPrimaryLight: "#3995ec",
      colorTerciary:"#ff7777",
      radiusSm: "8px",
      radiusLg: "16px",
      typographyBodyNormalFontFamily: "PoppinsMedium",
      colorAlertSuccessDark: "#53A335",
      colorAlertDetection: "#257CD0",
      colorAlertWarning: "#EB8D00",
      colorNeutral80: "#333333",
      shadowSm: "none",
      typographyBodyRegularFontFamily: "PoppinsRegular"
    },
    common: {
      ui: {
        logo: { show: true, media: "veridasLogo.png" },
        closeButton: { show: true, media: "closeButton.svg" },
        successTick: { show: true },
      },
      behavior: {
        common: {
          selectCamera: "front",
        },
        web: {
          logEvents: true,
          pathAssets: "assets",
        },
      },
    },
  },
  sdkSelfie: {
    "flowType": "selfie",
    views: {
      capture: {
        head: {
          token: "",
        },
      },
    },
  },
};

// Selfie instance, available sdk events, aliveChallenge token
let VDSelfie, SdkEvents, aliveChallenge;

// 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.vdSelfie.VDSelfie.events;
  addListeners();
}


/**
 * @name handleEvent
 * @description Handles the SDK events for the events in the eventHandlers object
 * @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)
      })
  })
}

/**
 * @name handleRestartProcess
 * @description Event handler for the SDK restartProcess event to restart the process with the alive challenge token. If the code is 8000 or 8001, the alive challenge token is updated with the new one. 8000 is for the challenge invalid head token and 8001 is for the error in the challenge.
 */
function handleRestartProcess(e) {
  if ([8000, 8001, 8002].includes(e.detail.code)) {
      aliveChallenge = VDSelfie.getJWTChallenge()
      if (window.e2eTestConfig) {
          window.e2eTestConfig.sdkSelfie.views.capture.head.token = aliveChallenge
      }
      VDSelfie.restartChallenge(aliveChallenge)
  }
}

async function onSDKMounted() {
  if (!VDSelfie) {
    VDSelfie = document.querySelector("vd-selfie");
  }
  
  aliveChallenge = VDSelfie.getJWTChallenge()
  localStorage.setItem('selfieToken', aliveChallenge)

  if (isConfigByFile) {
    await VDSelfie.initializeSdk('./config.json')
  } else if (configObject) {
    configObject.sdkSelfie.views.capture.head.token = aliveChallenge
    await VDSelfie.initializeSdk(configObject)
  } else {
    await VDSelfie.initializeSdk(null, aliveChallenge)
  }
}

/**
 * Starts the demo by replacing the button element with SDK VDSelfie custom element.
 * @function
 * @returns {void}
 */
const startDemo = () => {
  const elementApp = document.getElementsByClassName('element-app')[0];
  const buttonElement = document.getElementsByTagName('button')[0];
  buttonElement.remove();

  elementApp.innerHTML = `   
      <my-element id="myelement">
          <div class="container">
              <vd-selfie></vd-selfie>
          </div>
      </my-element>   
  `;
};
