'use strict';

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

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

// CONSTANTS
const constants = require('./constants');



module.exports.generate = (name, scope, groupId) => {

  tools.logTitle('Generating package');

  const artifactId = scope.substr(1, scope.length) + '-' + name + '-backend';

  const targetPath = path.join(constants.TARGET_ROOT_PATH, artifactId);


  return Promise.resolve()

    // CLEANING TARGET
    .then(() => {
      tools.logInfo('Cleaning target');
      return tools.rimraf(targetPath + '/**/*');
    })


    // COPY TO TARGET
    .then(() => {
      tools.logInfo('Copying skeleton to target');
      return tools.copydir(constants.BACKEND_SKELETON_PATH, targetPath, true);
    })


    // REPLACING PLACEHOLDERS
    .then(() => {
      tools.logInfo('Replacing placeholders');

      return Promise.resolve()
        .then(() => {
          return tools.replaceInPath(targetPath, '@groupId@', groupId);
        })
        .then(() => {
          return tools.replaceInPath(targetPath, '@artifactId@', artifactId);
        })
        .catch((e) => {
          throw e;
        })
    })

    .then(() => {
      tools.logInfo('Executing post build operations');
      return tools.move(path.join(targetPath, 'gitignore_TO_REPLACE'), path.join(targetPath, '.gitignore'));
    })

    .then(() => {
      const pkg = {
        name: artifactId,
        repoName: `${artifactId}.git`
      };

      // ADDING CONFIG ENTRY - specific csdr-remotes as of v15+
      tools.logInfo('Adding CSDR config entry');
      configUtils.register.registerCsdrPackage(
        pkg,
        scope, name, null,
        false,
        null,
        true
      );
    })

    .then(() => {
      tools.logSuccess();
    })

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



