"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.route = route;
exports.runCommand = runCommand;

var _fs = require("fs");

var _path = require("path");

var _allCommandsConfigs = _interopRequireDefault(require("./allCommandsConfigs"));

var _logger = require("./logger");

var _readOptions = require("./schemas/readOptions");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function runCommand(commandConfig, options) {
  const {
    dirname
  } = commandConfig;

  function runRespectiveFile(name, data) {
    const commandExecutorPath = (0, _path.join)(dirname, `${name}.js`);

    if ((0, _fs.existsSync)(commandExecutorPath)) {
      // eslint-disable-next-line import/no-dynamic-require, global-require
      const commandExecutor = require(commandExecutorPath);

      return (commandExecutor[name] || commandExecutor.default)(data);
    }

    (0, _logger.verboseLogger)('file not found', commandExecutorPath);
    return null;
  }

  const processedOption = runRespectiveFile('optionsProcessor', options) || options;
  runRespectiveFile('deprecationHandler', processedOption); // runRespectiveFile("errorHandler", () => {

  runRespectiveFile('preProcessor', processedOption);
  runRespectiveFile('commandExecutor', processedOption);
  runRespectiveFile('postProcessor', processedOption); // });
}

function route(option, args) {
  // TODO:  need to modify this log
  (0, _logger.verboseLogger)(`the command was ${option}`, args); // eslint-disable-next-line no-use-before-define

  const commandConfig = findCommandConfig(option);

  if (commandConfig) {
    try {
      const options = (0, _readOptions.getOptions)();
      runCommand(commandConfig, options);
    } catch (error) {
      (0, _logger.errorLogger)(error);
    }
  } else {
    // TODO: need to  write proper error message
    (0, _logger.warnLogger)('Un known command', option, 'please check the document');
  }
}

function findCommandConfig(option) {
  // eslint-disable-next-line no-restricted-syntax
  for (const commandConfig of _allCommandsConfigs.default) {
    if (commandConfig.name === option || commandConfig.alias.includes(option)) {
      return commandConfig;
    }
  }

  return null;
}