'use strict';

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

const buildPackageUtils = require('./build-package-utils');

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

module.exports.build = () => {
  tools.logTitle('Building all local packages');

  return Promise.resolve()

    // getting local packages with deps build order
    .then(() => {
      return configUtils.packages.getBuildablePackagesWithDeps()
        .map((p) => {
          return configUtils.packages.getPackage(p);
        });
    })

    // iterate over all packages and clean them individually
    .then((packages) => {
      if (packages.length > 0) {
        tools.logInfo(`Local packages found : (total: ${packages.length})\n[${packages.map(p => p.name)}]`);

        return packages.reduce((promise, pkg) => {
          return promise
            .then(() => buildPackageUtils.build(pkg))
            .catch((e) => {
              throw e;
            });
        }, Promise.resolve());
      }
    })

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