'use strict';

/*
    PRE-BUILD / INJECTION / CONFIG

    purpose:
      Inject config into project assets coming from remote packages either locally installed / from node_modules
    used by:
      MyWorkplace for openId config and routes config injection
    triggered by:
      presence of "config" array in CSDR App config entries

    public methods
      injectConfig(project)
*/


/* IMPORTS */

const path = require('path');

const tools = require('../../tools');
const configUtils = require('../../../csdr/config/config-utils');


/* PRIVATE METHODS */

const injectConfigCore = (project, npmPkg, folder = 'assets') => {
  // check if package is locally cloned
  const localPackage = configUtils.packages.getPackages().filter((p) => {
    return p.npmPkg === npmPkg
  })[0];

  var pkgAssetsPath;
  const projectAssetsPath = path.join(process.cwd(), project.folder, 'src', 'assets');
  const projectEnvironmentsPath = path.join(process.cwd(), project.folder, 'src', 'environments');

  // if local package is found
  if (localPackage) {
    pkgAssetsPath = path.join(process.cwd(), 'packages', localPackage.name, folder);

  // if not sources are taken from the npm package def in node_modules
  } else {
    const npmPkgScope = npmPkg.substr(0, npmPkg.indexOf('/'));
    const npmPkgName = npmPkg.substr(npmPkg.indexOf('/') + 1);
    pkgAssetsPath = path.join(process.cwd(), 'node_modules', npmPkgScope, npmPkgName, folder);
  }

  if (!tools.isDirExists(pkgAssetsPath)) {
    tools.logWarning(`Linked config pkg : ${npmPkg} cannot be found in node_modules`);
    return;
  }

  tools.logInfo(`${npmPkg}/assets - injecting in ${projectAssetsPath}`);
  tools.copydir(pkgAssetsPath, projectAssetsPath);

  const pkgEnvironmentsPath = path.join(pkgAssetsPath, 'environments');
  if (tools.isDirExists(pkgEnvironmentsPath)) {
    tools.logInfo(`${npmPkg}/assets/environments - injecting in ${projectEnvironmentsPath}`);
    tools.copydir(pkgEnvironmentsPath, projectEnvironmentsPath);
  }
}


/* PUBLIC METHODS */

module.exports.injectConfig = (project) => {

  tools.logTitle('Injecting project external config');

  return Promise.resolve()
    .then(() => {
      if (!project.config) {
        tools.logWarning('No linked config package found in project config');
        return;
      }

      // multi-config defined : api config and routes config for MWP
      if (Array.isArray(project.config)) {
        project.config.forEach((configNpmPkg) => {
          injectConfigCore(project, configNpmPkg);
        })

      // single config/npm package defined
      } else {
        console.log(project.config.folder)
        injectConfigCore(project, project.config.npmPkg, project.config.folder);
      }
    })

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