'use strict';

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

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

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

// INNER MODULES
const prompt = require('./package-prompt');
const buildBackend = require('./package-build-backend');
const buildFrontend = require('./package-build-frontend');


const generateArgs = (args) => {
  let npmPkgName, repoName;
  let fullName = args.pkgScope.substring(1) + '-' + args.pkgName;

  if (args.pkgFrontendType === constants.CONFIG_OPTIONS.pkgFrontendType.DEFAULT) {
    fullName += '-ui';
    npmPkgName = `${args.pkgScope}/${args.pkgName}`;

  } else if (args.pkgFrontendType === constants.CONFIG_OPTIONS.pkgFrontendType.REMOTE) {
    if (args.pkgFrontendVersion === constants.CONFIG_OPTIONS.pkgFrontendVersion.EUI19) {
      fullName += '-eui19-remote-el-ui';
      npmPkgName = `${args.pkgScope}/${args.pkgName}-eui19-remote-el`;
    }
  }

  // generating default git repo
  if (args.isCsdrRepo) {
    repoName = `${fullName}.git`;
  } else {
    repoName = `${args.externalRepoName}/${fullName}.git`;
  }

  return {
    ...args,
    fullName,
    npmPkgName,
    repoName,
  };
}


module.exports.generateExternal = (args) => {
  return Promise.resolve()
    .then(() => {
      // merging with defaults
      const answers = { ...constants.DEFAULT_CONFIG, ...args};

      // FRONTEND
      if (answers.pkgType === constants.CONFIG_OPTIONS.pkgType.FRONTEND) {
        const args = generateArgs(answers);

        tools.logInfo('Generated options :');
        console.log(args);

        return buildFrontend.generate(args);

      // BACKEND
      } else if (answers.pkgType === constants.CONFIG_OPTIONS.pkgType.BACKEND) {
        return buildBackend.generate(answers.pkgName, answers.pkgScope, answers.pkgGroupId);
      }
    })
    .catch((e) => {
      throw e;
    })
}



module.exports.generate = () => {

  return Promise.resolve()
    .then(() => {
      tools.logTitle('Please answer the following questions : ');
    })

    .then(() => {
      return prompt.prompt();
    })

    .then((answers) => {
      // merging with defaults
      answers = { ...constants.DEFAULT_CONFIG, ...answers};

      tools.logInfo('Provided options :');
      console.log(answers);

      // FRONTEND
      if (answers.pkgType === constants.CONFIG_OPTIONS.pkgType.FRONTEND) {
        const args = generateArgs(answers);

        return buildFrontend.generate(args);

      // BACKEND
      } else if (answers.pkgType === constants.CONFIG_OPTIONS.pkgType.BACKEND) {
        return buildBackend.generate(answers.pkgName, answers.pkgScope, answers.pkgGroupId);
      }
    })

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