"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.CHOOSE_CUSTOM_COMPILER_MSG_Q = exports.CHOOSE_COMPILER_MSG_Q = exports.CHOOSE_CUSTOM_ENV_MSG_TEMPLATE_Q = exports.CHOOSE_ENV_MSG_TEMPLATE_Q = exports.DEFAULT_DIR_MSG_Q = exports.PACKAGE_MANAGER_MSG_Q = exports.TOP_MESSAGE = void 0;

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _inquirer() {
  const data = _interopRequireDefault(require("inquirer"));

  _inquirer = function () {
    return data;
  };

  return data;
}

function _stringFormat() {
  const data = _interopRequireDefault(require("string-format"));

  _stringFormat = function () {
    return data;
  };

  return data;
}

function _chalk() {
  const data = _interopRequireDefault(require("chalk"));

  _chalk = function () {
    return data;
  };

  return data;
}

function _consumer() {
  const data = require("../../api/consumer");

  _consumer = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

_inquirer().default.registerPrompt('fuzzypath', require('inquirer-fuzzy-path'));

const TOP_MESSAGE = `This utility initialize an empty Bit workspace and walks you through creating a bit configuration.

You can later edit your configuration in your package.json or bit.json.

After setting up the workspace, use 'bit add' to track components and modules.

To disable interactive mode run 'bit config set interactive.init false' or use 'bit init -N'.

Press ^C at any time to quit.`;
exports.TOP_MESSAGE = TOP_MESSAGE;
const PACKAGE_MANAGER_MSG_Q = 'Which package manager would you like to use for installing components?';
exports.PACKAGE_MANAGER_MSG_Q = PACKAGE_MANAGER_MSG_Q;
const DEFAULT_DIR_MSG_Q = 'Where would you like to store imported components?';
exports.DEFAULT_DIR_MSG_Q = DEFAULT_DIR_MSG_Q;
const CHOOSE_ENV_MSG_TEMPLATE_Q = 'Which {type} would you like to use for the components?';
exports.CHOOSE_ENV_MSG_TEMPLATE_Q = CHOOSE_ENV_MSG_TEMPLATE_Q;
const CHOOSE_CUSTOM_ENV_MSG_TEMPLATE_Q = 'Paste the "bit import" command for the {type} (press "enter" to skip).';
exports.CHOOSE_CUSTOM_ENV_MSG_TEMPLATE_Q = CHOOSE_CUSTOM_ENV_MSG_TEMPLATE_Q;
const CHOOSE_COMPILER_MSG_Q = (0, _stringFormat().default)(CHOOSE_ENV_MSG_TEMPLATE_Q, {
  type: 'compiler'
}); // export const CHOOSE_TESTER_MSG_Q = format(CHOOSE_ENV_MSG_TEMPLATE_Q, { type: 'tester' });

exports.CHOOSE_COMPILER_MSG_Q = CHOOSE_COMPILER_MSG_Q;
const CHOOSE_CUSTOM_COMPILER_MSG_Q = (0, _stringFormat().default)(CHOOSE_CUSTOM_ENV_MSG_TEMPLATE_Q, {
  type: 'compiler'
});
exports.CHOOSE_CUSTOM_COMPILER_MSG_Q = CHOOSE_CUSTOM_COMPILER_MSG_Q;
const SKIP_DEFINE_ENV_TEMPLATE_ANS = 'no {type}';
const SKIP_DEFINE_COMPILER_ANS = (0, _stringFormat().default)(SKIP_DEFINE_ENV_TEMPLATE_ANS, {
  type: 'compiler'
}); // const SKIP_DEFINE_TESTER_ANS = format(SKIP_DEFINE_ENV_TEMPLATE_ANS, { type: 'tester' });

const CUSTOM_ENV_TEMPLATE_ANS = 'I have my own {type}';
const CUSTOM_COMPILER_ANS = (0, _stringFormat().default)(CUSTOM_ENV_TEMPLATE_ANS, {
  type: 'compiler'
}); // const CUSTOM_TESTER_ANS = format(CUSTOM_ENV_TEMPLATE_ANS, { type: 'tester' });

const SKIP_CUSTOM_ENV_KEYWORD = 'skip';
const BIT_ENVS_SCOPE_NAME = 'bit.envs';
const CUSTOM_COMPILER_PROP_NAME = 'custom-compiler';
const DEFAULT_LOCATION_DIR = 'components';
const DEFAULT_LOCATION_NOTE = "(bit's default location)";
const DEFAULT_LOCATION_ANS = `${DEFAULT_LOCATION_DIR} ${DEFAULT_LOCATION_NOTE}`;

function _generateChooseEnvQ(envType, propName, message, skipAnsTxt, customEnvAnsTxt) {
  let components = []; // Fetch the components from the remote. If there was an error or no components returned we will skip the question.
  // We will store the returned components in a higher scope, to prevent another request during the choices calculation

  const whenWithFetch =
  /*#__PURE__*/
  function () {
    var _ref = (0, _bluebird().coroutine)(function* () {
      try {
        components = yield _fetchEnvs(envType);

        if (!components || !components.length) {
          // eslint-disable-next-line no-console
          console.log(_chalk().default.yellow('no components found. skipping question'));
          return false;
        }

        return true;
      } catch (e) {
        // eslint-disable-next-line no-console
        //  console.log(
        //  chalk.yellow(`could not retrieve compilers list.
        // see full error log in ${DEBUG_LOG}
        // you can add a compiler later using bit import [compiler-name] --${envType}`)
        //      );
        _logger().default.info(e);

        return true;
      }
    });

    return function whenWithFetch() {
      return _ref.apply(this, arguments);
    };
  }();

  const choices = () => {
    const choicesArr = [skipAnsTxt, new (_inquirer().default.Separator)()];

    if (components && components.length) {
      choicesArr.push(...components);
      choicesArr.push(new (_inquirer().default.Separator)());
    }

    choicesArr.push(customEnvAnsTxt);
    choicesArr.push(new (_inquirer().default.Separator)());
    return choicesArr;
  };

  const selectEnv = {
    type: 'list',
    name: propName,
    message,
    when: whenWithFetch,
    choices
  };
  return selectEnv;
}

function _generateChooseCustomEnvQ(envType, propName, message, propToCheck, valToCheck) {
  const when = answers => {
    return answers[propToCheck] === valToCheck;
  };

  const customEnv = {
    type: 'input',
    name: propName,
    message,
    when
  };
  return customEnv;
}

function _fetchEnvs(_x) {
  return _fetchEnvs2.apply(this, arguments);
}

function _fetchEnvs2() {
  _fetchEnvs2 = (0, _bluebird().coroutine)(function* (envType) {
    if (envType === 'compiler') {
      return _fetchCompilers();
    }

    return _fetchTesters();
  });
  return _fetchEnvs2.apply(this, arguments);
}

function _fetchCompilers() {
  return _fetchCompilers2.apply(this, arguments);
}

function _fetchCompilers2() {
  _fetchCompilers2 = (0, _bluebird().coroutine)(function* () {
    return _fetchComps(BIT_ENVS_SCOPE_NAME, ['compilers', 'bundlers']);
  });
  return _fetchCompilers2.apply(this, arguments);
}

function _fetchTesters() {
  return _fetchTesters2.apply(this, arguments);
}

function _fetchTesters2() {
  _fetchTesters2 = (0, _bluebird().coroutine)(function* () {
    return _fetchComps(BIT_ENVS_SCOPE_NAME, ['testers']);
  });
  return _fetchTesters2.apply(this, arguments);
}

function _fetchComps(_x2) {
  return _fetchComps2.apply(this, arguments);
}

function _fetchComps2() {
  _fetchComps2 = (0, _bluebird().coroutine)(function* (scopeName, namespaces = []) {
    // Filter the namespace on the remote
    const namespacesUsingWildcards = namespaces.length ? `${namespaces.join('|')}/*` : undefined; // Not using user/pass strategy since it will interrupt the flow

    const strategiesNames = ['token', 'ssh-agent', 'ssh-key'];
    const listScopeResults = yield (0, _consumer().listScope)({
      scopeName,
      showAll: false,
      showRemoteVersion: true,
      namespacesUsingWildcards,
      strategiesNames
    });
    const ids = listScopeResults.map(result => result.id.toString());
    return ids;
  });
  return _fetchComps2.apply(this, arguments);
}

function _buildQuestions() {
  return _buildQuestions2.apply(this, arguments);
}

function _buildQuestions2() {
  _buildQuestions2 = (0, _bluebird().coroutine)(function* () {
    const packageManagerQ = {
      type: 'list',
      name: 'packageManager',
      message: PACKAGE_MANAGER_MSG_Q,
      choices: ['npm', 'yarn']
    }; // TODO: 1. the suggestOnly is the opposite, this is a bug in https://github.com/mokkabonna/inquirer-autocomplete-prompt/blob/master/index.js
    // TODO: 2. add option for the default ./components add support for adding extra values in (https://github.com/adelsz/inquirer-fuzzy-path)

    const componentsDirQ = {
      type: 'fuzzypath',
      name: 'componentsDefaultDirectory',
      excludePath: nodePath => {
        return nodePath.startsWith('node_modules') || nodePath.startsWith('.bit') || nodePath.startsWith('.git');
      },
      // excludePath :: (String) -> Bool
      // excludePath to exclude some paths from the file-system scan
      itemType: 'directory',
      // itemType :: 'any' | 'directory' | 'file'
      // specify the type of nodes to display
      // default value: 'any'
      // example: itemType: 'file' - hides directories from the item list
      rootPath: '.',
      // rootPath :: String
      // Root search directory
      message: DEFAULT_DIR_MSG_Q,
      default: DEFAULT_LOCATION_ANS,
      suggestOnly: false // suggestOnly :: Bool
      // Restrict prompt answer to available choices or use them as suggestions

    };

    const chooseCompilerQ = _generateChooseEnvQ('compiler', 'compiler', CHOOSE_COMPILER_MSG_Q, SKIP_DEFINE_COMPILER_ANS, CUSTOM_COMPILER_ANS);

    const chooseCustomCompilerQ = _generateChooseCustomEnvQ('compiler', CUSTOM_COMPILER_PROP_NAME, CHOOSE_CUSTOM_COMPILER_MSG_Q, 'compiler', CUSTOM_COMPILER_ANS);

    return [packageManagerQ, componentsDirQ, chooseCompilerQ, chooseCustomCompilerQ];
  });
  return _buildQuestions2.apply(this, arguments);
}

var _default =
/*#__PURE__*/
function () {
  var _initInteractive = (0, _bluebird().coroutine)(function* () {
    const ui = new (_inquirer().default.ui.BottomBar)();
    ui.log.write(TOP_MESSAGE);
    const questions = yield _buildQuestions();
    const answers = yield _inquirer().default.prompt(questions);

    if (answers.componentsDefaultDirectory === DEFAULT_LOCATION_ANS) {
      // Remove the default location note
      answers.componentsDefaultDirectory = DEFAULT_LOCATION_DIR;
    }

    answers.componentsDefaultDirectory = `${answers.componentsDefaultDirectory}/{name}`;
    let actualCompiler = answers.compiler;

    if (actualCompiler === CUSTOM_COMPILER_ANS) {
      actualCompiler = answers[CUSTOM_COMPILER_PROP_NAME];

      if (actualCompiler.startsWith('bit import')) {
        // remove bit import copied from the bit.dev
        actualCompiler = actualCompiler.replace('bit import ', '');
      }

      if (actualCompiler.toLowerCase() === SKIP_CUSTOM_ENV_KEYWORD) {
        actualCompiler = undefined;
      }
    } else if (actualCompiler === SKIP_DEFINE_COMPILER_ANS) {
      actualCompiler = undefined;
    }

    answers.compiler = actualCompiler;
    return (0, _consumer().init)(undefined, false, false, false, false, answers).then(({
      created,
      addedGitHooks,
      existingGitHooks
    }) => {
      return {
        created,
        addedGitHooks,
        existingGitHooks,
        reset: false,
        resetHard: false
      };
    });
  });

  function initInteractive() {
    return _initInteractive.apply(this, arguments);
  }

  return initInteractive;
}();

exports.default = _default;