'use strict';

// GLOBAL
const path = require('path');

// LOCAL
const tools = require('../../utils/tools');
const injectionUtils = require('../../utils/pre-build/injection/injection-utils');
const configUtils = require('../config/config-utils');



module.exports.importScripts = () => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle("Init scripts for local projects");
      const projects = configUtils.projects.getProjects();

      const rootPackageJsonFile = path.join(process.cwd(), 'package.json')
      const rootPackageJson = require(rootPackageJsonFile);

      projects.forEach((p) => {
        tools.logInfo(`Project :  ${p.name}`);

        const scriptsFile = path.join(process.cwd(), p.folder, 'scripts.json');
        if (!tools.isFileExists(scriptsFile)) {
          tools.logInfo('no scripts.json file found - skipping');
        } else {
          tools.logInfo('Processing scripts.json file');
          const scriptsJson = require(scriptsFile);
          rootPackageJson.scripts = { ...rootPackageJson.scripts, ...scriptsJson };
        }
      });

      tools.logInfo('Updating root package.json');
      tools.writeJsonFileSync(rootPackageJsonFile, rootPackageJson);
    })
    .catch((e) => {
      throw e;
    })
}


module.exports.importExternalFeatures = () => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle("Import external features for local projects");

      return configUtils.projects.getProjects().reduce((promise, prj) => {
        return promise.then(() => (
          injectionUtils.externals.injectExternalFeatures(prj)
        ));
      }, Promise.resolve());
    })
    .catch((e) => {
      throw e;
    })
}


module.exports.importExternalSources = (init = false) => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle("Import external sources for local projects");

      return configUtils.projects.getProjects().reduce((promise, prj) => {
        return promise.then(() => (
          injectionUtils.externals.injectExternalAppSources(prj, false, init)
        ));
      }, Promise.resolve());
    })
    .catch((e) => {
      throw e;
    })
}



module.exports.importExternalMock = () => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle("Import external mock for local projects");

      return configUtils.projects.getProjects().reduce((promise, prj) => {
        return promise.then(() => (
          injectionUtils.externals.injectExternalMock(prj)
        ));
      }, Promise.resolve());

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



module.exports.importExtraTsConfig = () => {
  tools.logTitle("Init extra ts config for local projects");

  return Promise.resolve()
    .then(() => {

      configUtils.projects.getProjects().forEach((p) => {
        tools.logInfo(`Check extra tsconfig for project :  ${p.name}`);
        configUtils.angular.registerProjectExtraPaths(p);
      })
    })
    .catch((e) => {
      throw e;
    })
}
