import { WebDriver } from 'selenium-webdriver';
import { executeWithModules } from './oj-module-proxy';

/**
 * Check the running JET UI version against this oraclejet-webdriver package
 * version. It's expected that the JET UI is already fully loaded so that
 * "oj.version" and "oj.revision" will resolve.
 * If a mismatch is found, a console warning will be logged with the mismatched
 * values.
 * @param driver WebDriver instance
 * @private
 */
export async function checkVersions(driver: WebDriver) {
  const pjson = require('../package.json');
  const version = pjson.version;
  const revision = pjson.config.revision;
  const jet = await executeWithModules<{ version: string; revision: string }>(
    driver,
    ['Core'],
    [],
    (core) => ({ version: core.version, revision: core.revision })
  );
  if (
    // Check if not local build (running from JET repo)
    !revision.match(/^#@@oj\.revision@@#$|^local:/) &&
    // or version mismatch
    (version !== jet.version || revision !== jet.revision)
  ) {
    const mismatch = `version mismatch: oraclejet ${JSON.stringify(
      jet
    )}, oraclejet-webdriver ${JSON.stringify({ version, revision })}`;
    console.warn(`
  Your oraclejet UI version/revision does not match oraclejet-webdriver
  ${mismatch}
      `);
    throw Error(mismatch);
  }
}
