'use strict';

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

const cleanUtils = require('./clean-utils');


module.exports.clean = () => {
  tools.logTitle('Cleaning all local packages');

  return Promise.resolve()

    // getting local packages
    .then(() => {
      return configUtils.packages.getBuildablePackages()
        .map((p) => {
          return configUtils.packages.getPackage(p.name);
        });
    })

    // 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(() => cleanUtils.cleanPackage(pkg))
            .catch((e) => {
              throw e;
            });
        }, Promise.resolve());
      }
    })

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