'use strict';

const path = require('path');

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

const translationUtils = require('./translations/translation-utils');
const configUtils = require('../../csdr/config/config-utils');
const injectionUtils = require('./injection/injection-utils');
const initUtils = require('../../csdr/init/init-utils');

module.exports.preBuild = (pkg, build = false) => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle('PRE-BUILD : preparing the remote element...')
    })

    .then(() => {
      if (pkg.virtual && !pkg.standalone) {
        return initUtils.remotes.generateVirtualRemote(pkg.name, false);
      }
    })

    .then(() => {
      tools.logInfo('Registering angular project definition...');
      return configUtils.angular.registerAngularProjectDef(pkg, build, true);
    })

    .then(() => {
      if (build) {
        return;
      }

      tools.logInfo('Registering element tsconfig local paths...');

      const tsConfigFile = path.join(pkg.paths.root, 'tsconfig.app.json');
      const tsConfig = require(tsConfigFile);

      const copyRootPkgDist = (localPkg) => {
        tools.logInfo('Copying root pkg dist folder to remote node_modules');

        const nmPath = path.join(pkg.paths.root, 'node_modules');
        const nmPkgScopePath = path.join(nmPath, localPkg.npmPkgScope);
        const nmPkgPath = path.join(nmPkgScopePath, localPkg.npmPkgName);
        const pkgDistPath = path.join(localPkg.paths.root, 'dist');

        if (!tools.isDirExists(pkgDistPath)) {
          tools.logWarning(`Package dist folder can't be found, build it before serving the remote locally : ${pkgDistPath}`);
          throw new Error('ROOT_PACKAGE_DIST_NOT_FOUND');
        }

        if (!tools.isDirExists(nmPkgPath)) {
          tools.copydir(pkgDistPath, nmPkgPath);
        }
      }

      if (pkg.registerLocalRootPkg && pkg.skeletonConfig) {
        const localPkg = configUtils.packages.getPackageByNpmPkg(pkg.skeletonConfig.rootNpmPkg);
        copyRootPkgDist(localPkg);
      }

      tools.writeJsonFileSync(tsConfigFile, tsConfig);
    })

    // inject external app sources declaration
    .then(() => {
      if (pkg.externalSources) {
        return injectionUtils.externals.injectElementExternalSources(pkg);
      }
    })

    .then(() => {
      tools.logInfo('Checking compiled translations');
      if (pkg.build && pkg.build.compiledTranslations) {
        const scopes = pkg.build.translationScopes;
        if (scopes) {
          return translationUtils.elements.generate(scopes, pkg);
        } else {
          return translationUtils.elements.generate(pkg);
        }

      } else {
        tools.logInfo('no compiled translations found...skipping');
      }
    })

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