"use strict";

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

var _fs = require("fs");

var _path = require("path");

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

var _buildToolLoggers = require("./buildToolLoggers");

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

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

function runCommand(commandConfig) {
  const options = (0, _readOptions.getOptions)();
  const {
    dirname
  } = commandConfig;

  function runRespectiveFile(name, data) {
    const commandExecutorPath = (0, _path.join)(dirname, name + ".js");

    if ((0, _fs.existsSync)(commandExecutorPath)) {
      const commandExecutor = require(commandExecutorPath);

      return (commandExecutor[name] || commandExecutor.default)(data);
    } else {
      (0, _buildToolLoggers.debugLogger)("file not found", commandExecutorPath);
    }
  }

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

  runRespectiveFile("preProcesser", processedOption);
  runRespectiveFile("commandExecutor", processedOption);
  runRespectiveFile("postProcesser", processedOption); // });
}

function route(option, args) {
  // TODO:  need to modify this log
  (0, _buildToolLoggers.debugLogger)("the command was " + option, args);
  const commandConfig = findCommandConfig(option);

  if (commandConfig) {
    try {
      runCommand(commandConfig);
    } catch (error) {
      console.error(error);
    }
  } else {
    // TODO: need to  write proper error message
    (0, _buildToolLoggers.warnLogger)("Un known command", option, "please check the document");
  }
}

function findCommandConfig(option) {
  for (const commandConfig of _allCommandsConfigs.default) {
    if (commandConfig.name === option || commandConfig.alias.includes(option)) {
      return commandConfig;
    }
  }

  return null;
}