import { init, mountWidget } from './index.esm.js';

/***
 * initAiwareUi - initialize the aiware.js ui and mount the app bar widget
 * @param {Object} initConfig - the required config object to be passed to aiware.init
 * @param {Object} appBarConfig - the optional config object to be passed to aiware.mountWidget
 * @return {Promise<{ token: String, widgetId?: String }>} - the user's session token
 */
const initAiwareUi = (initConfig, appBarConfig) => {
  return new Promise((resolve, reject) => {
    const resolveAll = widgetId => token => {
      resolve({
        token,
        widgetId,
      });
    };
    if (!initConfig) {
      reject('the init config argument is required');
    } else {
      init(initConfig, (err, token) => {
        if (appBarConfig) {
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          let finalResolve = () => {};
          const widgetId = mountWidget(appBarConfig, () => {
            if (err) {
              reject(err);
            } else {
              finalResolve(token);
            }
          });
          finalResolve = resolveAll(widgetId);
        } else if (err) {
          reject(err);
        } else {
          resolve({ token });
        }
      });
    }
  });
};

if (window) {
  window['initAiwareUi'] = initAiwareUi;
}

export { initAiwareUi, init, mountWidget };
