import {LpSetupConfig, LpInitConfig, LpChatConfig} from './lp-types';

import {getLpLocale, getSDEs} from './utils/utils';
import {getCurrentConfig} from './config/config';
import { async } from 'q';

let currentChatConfig: LpChatConfig;
let currentEngagementId = 0;

const getEngagementId = (locale: string): number => {
  const chatConfig = currentChatConfig.locales[locale];
  return locale === 'en' ? chatConfig.lpMessaging : chatConfig.default!;
};

const getLpDivId = () => `LP_DIV_${currentEngagementId}`;

const createLpContainer = () => {
  const id = getLpDivId();
  if (!window.document.getElementById(`${id}`)) {
    const el = window.document.createElement('div');
    el.setAttribute('id', id);
    window.document.body.append(el);
  }
};

export const updateEngagement = (locale: string) => {
  createLpContainer();
  window.lpTag?.newPage?.(window.location.href, {
    section: [locale],
    sdes: [],
    taglets: {
      rendererStub: {
        divIdsToKeep: {
          [getLpDivId()]: true,
        },
      },
    },
  });
};

export const setup = ({locale}: LpSetupConfig) => {
  if (currentEngagementId) return;
  const lpLocale = getLpLocale(locale);
  currentChatConfig = getCurrentConfig();
  currentEngagementId = getEngagementId(lpLocale);
  if (!currentEngagementId) return;
  updateEngagement(lpLocale);
};

export const init = ({locale}: LpInitConfig) => {
  if (!currentChatConfig) throw new Error('Setup must be called before init');
  const lpLocale = getLpLocale(locale);
  const engagementId = getEngagementId(lpLocale);
  console.log(lpLocale, engagementId);
  
  if (engagementId !== currentEngagementId) {
    currentEngagementId = engagementId;
    updateEngagement(lpLocale);
  }
};

export const startChat = async ({locale}: LpInitConfig) => {
  window.lpTag.sdes = window.lpTag.sdes || [];
  const spoSDEs = await getSDEs();
  window.lpTag.sdes.push(spoSDEs);
  const lpLocale = locale;
  updateEngagement(lpLocale);
  window.lpTag.taglets.rendererStub.click(currentEngagementId, {});
};