'use strict';

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

// LOCAL
const tools = require('../../tools');
const notificationUtils = require('../../notification/notification-utils');
const testUtils = require('../../test/test-utils');

// FETCH ARGS
let { skipLint, skipTest } = tools.getArgs();


module.exports.build = (pkg, isMaster) => {
  tools.logTitle('Building NodeJS package...');

  if (pkg.build) {
    if (pkg.build.skipTest) {
      skipTest = true;
    }
  }

  return Promise.resolve()
    .then(() => {
      if (!skipTest) {
        return testUtils.runMocha(pkg);
      }
    })
    .then(() => {
      return tools.copydir(
        path.join(pkg.paths.root, 'assets'),
        path.join(pkg.paths.dist, 'assets')
      );
    })
    .then(() => {
      console.log('assets copy succeeded');
      tools.copy(path.join(pkg.paths.root, 'package.json'), path.join(pkg.paths.dist, 'package.json'));
      tools.copy(path.join(pkg.paths.root, 'README.md'), path.join(pkg.paths.dist, 'README.md'));
      tools.copy(path.join(pkg.paths.root, 'LICENSE'), path.join(pkg.paths.dist, 'LICENSE'));
    })

    .then(() => {
      // throw new Error('FAKE FAILURE');

      return notificationUtils.package.sendPackageMessage({
        package: pkg
      })
    })

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