'use strict';

const path = require('path');

const tools = require('../../tools');

let { openid } = tools.getArgs();

module.exports.injectConfig = (project, configEnvTarget) => {
  return (
    Promise.resolve()

      .then(() => {
        tools.logTitle('PRE-BUILD : preparing the project...');
      })

      // openId files replacement
      .then(() => {
        if ((project.build && project.build.openid) || openid) {
          tools.logInfo('Executing scripts files replacement for openId Connect');

          const nodeModulesPath = project.paths.nodeModulesPath;
          let rootTargetFolder = 'src';

          tools.logInfo(`Copying ${nodeModulesPath}/oidc-client/dist/oidc-client.min.js to ${rootTargetFolder}/assets/oidc-client.min.js`);
          tools.copy(
            path.join(nodeModulesPath, '/oidc-client/dist/oidc-client.min.js'),
            path.join(project.paths.angularPath, `${rootTargetFolder}/assets/oidc-client.min.js`)
          );
          tools.logSuccess();

          tools.logInfo(`Copying ${nodeModulesPath}/jsrsasign/lib/jsrsasign-all-min.js to ${rootTargetFolder}/assets/jsrsasign-all-min.js`);
          tools.copy(
            path.join(nodeModulesPath, '/jsrsasign/lib/jsrsasign-all-min.js'),
            path.join(project.paths.angularPath, `${rootTargetFolder}/assets/jsrsasign-all-min.js`)
          );
          tools.logSuccess();

          let { configuration } = tools.getArgs();
          if (configuration !== 'proxy-mock') {
            if (project.build && project.build.providedOpenidLoginScript) {
              tools.logInfo(`Provided openid-login.js script...skipping copy from eUI distribution`);

            } else {
              tools.logInfo(`Copying ${nodeModulesPath}/@eui/base/assets/openid/openid-login.js to ${rootTargetFolder}/assets/openid-login.js`);
              tools.copy(
                path.join(nodeModulesPath, '/@eui/base/assets/openid/openid-login.js'),
                path.join(project.paths.angularPath, `${rootTargetFolder}/assets/openid-login.js`)
              );
            }
          } else {
            tools.logInfo(`Clearing ${rootTargetFolder}/assets/openid-login.js`);
            tools.writeFileContent(
              path.join(project.paths.angularPath, `${rootTargetFolder}/assets/openid-login.js`),
              ''
            );
          }
          tools.logSuccess();
        }
      })

      // injection config based on configEnvTarget (for openid files replacement)
      .then(() => {
        return injectAppConfig(project, configEnvTarget);
      })

      .catch((e) => {
        throw e;
      })
  );
};

// extracted from main openid injectConfig above as this can be called stand-alone using bin/eui-scripts

const injectAppConfig = (module.exports.injectAppConfig = (project, configEnvTarget) => {
  return Promise.resolve()
    .then(() => {
      // set default if not envTarget provided
      let envFilePath = path.join(project.paths.angularPath, 'src/assets/config', `env-json-config.json`);

      if (configEnvTarget) {
        tools.logInfo(`Executing configuration replacement for : ${configEnvTarget} environment`);

        let envOpenidPrefix = 'env-json-config-';
        if (project.build && project.build.envOpenidPrefix) {
          envOpenidPrefix = project.build.envOpenidPrefix;
        }

        let openidConfigAssetsFolder = 'assets/config';
        if (project.build && project.build.openidConfigAssetsFolder) {
          openidConfigAssetsFolder = project.build.openidConfigAssetsFolder;
        }
        envFilePath = path.join(project.paths.angularPath, `src/${openidConfigAssetsFolder}`, `${envOpenidPrefix}${configEnvTarget}.json`);
      }

      if (project.build && project.build.customEnvJsonConfigInjection) {
        return;
      }
      if (!tools.isFileExists(envFilePath)) {
        tools.logError(`Cannot find environment config to inject : `);
        tools.logError(`${envFilePath} missing...`);
        return;
      }

      let rootTargetFolder = 'src';
      let replacedFile;

      if ((project.build && project.build.openid) || openid) {
        replacedFile = `${rootTargetFolder}/assets/openid-login-config.json`;
      } else {
        replacedFile = `${rootTargetFolder}/assets/env-json-config.json`;
      }
      tools.logInfo(`Replacing default ${replacedFile} file by ${envFilePath} content`);
      tools.copy(envFilePath, path.join(project.paths.angularPath, `${replacedFile}`));

      tools.logSuccess();
    })

    .catch((e) => {
      throw e;
    });
});
