"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.shouldSkipTask = exports.registerCustomTask = exports.initializeTask = exports.findSuitableTask = exports.executeTask = exports.executeOrSkipTask = exports.executeEngineTask = void 0;var _logger = require("../systemManager/logger");
var _analytics = _interopRequireDefault(require("../systemManager/analytics"));
var _buildHooks = require("../projectManager/buildHooks");
var _prompt = require("../../cli/prompt");
var _npmUtils = require("../systemManager/npmUtils");
var _engineManager = require("../engineManager");
var _constants = require("../constants");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _typeof(obj) {"@babel/helpers - typeof";return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {return typeof obj;} : function (obj) {return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;}, _typeof(obj);}function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {Promise.resolve(value).then(_next, _throw);}}function _asyncToGenerator(fn) {return function () {var self = this,args = arguments;return new Promise(function (resolve, reject) {var gen = fn.apply(self, args);function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);}function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);}_next(undefined);});};}


var executedTasks = {};

var CUSTOM_TASKS = {};

var registerCustomTask = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c, task) {return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
            if (task.task) {
              CUSTOM_TASKS[task.task] = task;
            }case 1:case "end":return _context.stop();}}}, _callee);}));return function registerCustomTask(_x, _x2) {return _ref.apply(this, arguments);};}();exports.registerCustomTask = registerCustomTask;


var initializeTask = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, task) {return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('initializeTask', task);
            c.runtime.task = task;
            executedTasks = {};

            _analytics["default"].captureEvent({
              type: "".concat(task, "Project"),
              platform: c.platform });_context2.next = 6;return (


              executeTask(c, task, null, task, true));case 6:return _context2.abrupt("return",
            true);case 7:case "end":return _context2.stop();}}}, _callee2);}));return function initializeTask(_x3, _x4) {return _ref2.apply(this, arguments);};}();exports.initializeTask = initializeTask;


var _getTaskOption = function _getTaskOption(_ref3) {var taskInstance = _ref3.taskInstance,hasMultipleSubTasks = _ref3.hasMultipleSubTasks;
  if (hasMultipleSubTasks) {
    return "".concat(taskInstance.task.split(' ')[0], "...");
  }
  if (taskInstance.description && taskInstance.description !== '') {
    return "".concat(taskInstance.task.split(' ')[0], " ").concat((0, _logger.chalk)().grey("(".concat(taskInstance.description, ")")));
  }
  return "".concat(taskInstance.task.split(' ')[0]);
};

var _getTaskObj = function _getTaskObj(taskInstance) {
  var key = taskInstance.task.split(' ')[0];
  var hasMultipleSubTasks = false;
  if (taskInstance.task.includes(' ')) hasMultipleSubTasks = true;
  return {
    key: key,
    taskInstance: taskInstance,
    hasMultipleSubTasks: hasMultipleSubTasks };

};

var findSuitableTask = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c, specificTask) {var REGISTERED_ENGINES, task, suitableTaskInstances, taskInstances, tasks, defaultCmd, tasksCommands, filteredTasks, addendum, _yield$inquirerPrompt, command, suitableEngines, autocompleteEngines, isAutoComplete, message, supportedSubtasksArr, supportedSubtasks, supportedSubtasksFilter, subTasks, _yield$inquirerPrompt2, subCommand, customTask;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
            (0, _logger.logTask)('findSuitableTask');
            REGISTERED_ENGINES = (0, _engineManager.getRegisteredEngines)(c);if (

            specificTask) {_context3.next = 65;break;}if (
            c.command) {_context3.next = 16;break;}
            suitableTaskInstances = {};
            REGISTERED_ENGINES.forEach(function (engine) {
              Object.values(engine.tasks).forEach(function (taskInstance) {
                var taskObj = _getTaskObj(taskInstance);
                suitableTaskInstances[taskObj.key] = taskObj;
              });
            });
            Object.values(CUSTOM_TASKS).forEach(function (taskInstance) {
              var taskObj = _getTaskObj(taskInstance);
              suitableTaskInstances[taskObj.key] = taskObj;
            });

            taskInstances = Object.values(suitableTaskInstances);

            defaultCmd = 'new';


            addendum = '';
            if (!c.paths.project.configExists) {
              filteredTasks = taskInstances.filter(function (v) {return v.taskInstance.isGlobalScope;});
              tasks = filteredTasks.map(function (v) {return _getTaskOption(v);}).sort();
              tasksCommands = filteredTasks.map(function (v) {return v.taskInstance.task.split(' ')[0];}).sort();
              addendum = ' (Not a ReNative project. options will be limited)';
            } else {
              tasks = taskInstances.map(function (v) {return _getTaskOption(v);}).sort();
              tasksCommands = taskInstances.map(function (v) {return v.taskInstance.task.split(' ')[0];}).sort();
              defaultCmd = tasks.find(function (v) {return v.startsWith('run');});
            }_context3.next = 13;return (

              (0, _prompt.inquirerPrompt)({
                type: 'list',
                "default": defaultCmd,
                name: 'command',
                message: "Pick a command".concat(addendum),
                choices: tasks,
                pageSize: 15,
                logMessage: 'Welcome to the brave new world...' }));case 13:_yield$inquirerPrompt = _context3.sent;command = _yield$inquirerPrompt.command;

            c.command = tasksCommands[tasks.indexOf(command)];case 16:

            task = c.command;
            if (c.subCommand) task += " ".concat(c.subCommand);

            suitableEngines = REGISTERED_ENGINES.
            filter(function (engine) {return (0, _engineManager.hasEngineTask)(task, engine.tasks, c.paths.project.configExists);});

            autocompleteEngines = REGISTERED_ENGINES.
            filter(function (engine) {return (0, _engineManager.getEngineSubTasks)(task, engine.tasks, true).length;});

            isAutoComplete = !suitableEngines.length && !!c.command && !autocompleteEngines.length;
            message = isAutoComplete ? "Autocomplete action for \"".concat(
            c.command, "\"") : "Pick a subCommand for ".concat(c.command);if (

            suitableEngines.length) {_context3.next = 38;break;}
            // Get all supported tasks
            supportedSubtasksArr = [];
            REGISTERED_ENGINES.forEach(function (engine) {
              (0, _engineManager.getEngineSubTasks)(task, engine.tasks).forEach(function (taskInstance) {
                var isNotViable = !c.paths.project.configExists && !taskInstance.isGlobalScope;
                if (!isNotViable) {var _taskInstance$descrip, _taskInstance$descrip2;
                  var taskKey = isAutoComplete ? taskInstance.task : taskInstance.task.split(' ')[1];

                  supportedSubtasksArr.push({
                    desc: (_taskInstance$descrip = taskInstance.description) === null || _taskInstance$descrip === void 0 ? void 0 : (_taskInstance$descrip2 = _taskInstance$descrip.toLowerCase) === null || _taskInstance$descrip2 === void 0 ? void 0 : _taskInstance$descrip2.call(_taskInstance$descrip),
                    taskKey: taskKey });

                }
              });
            });
            Object.values(CUSTOM_TASKS).forEach(function (taskInstance) {
              var tskArr = taskInstance.task.split(' ');
              if (task === tskArr[0]) {var _taskInstance$descrip3, _taskInstance$descrip4;
                var taskKey = isAutoComplete ? taskInstance.task : taskInstance.task.split(' ')[1];

                supportedSubtasksArr.push({
                  desc: (_taskInstance$descrip3 = taskInstance.description) === null || _taskInstance$descrip3 === void 0 ? void 0 : (_taskInstance$descrip4 = _taskInstance$descrip3.toLowerCase) === null || _taskInstance$descrip4 === void 0 ? void 0 : _taskInstance$descrip4.call(_taskInstance$descrip3),
                  taskKey: taskKey });

              }
            });
            supportedSubtasks = {};
            // Normalize task options
            supportedSubtasksFilter = {};
            supportedSubtasksArr.forEach(function (tsk) {
              var mergedTask = supportedSubtasksFilter[tsk.taskKey];
              if (!mergedTask) {
                supportedSubtasksFilter[tsk.taskKey] = tsk;
              } else if (!mergedTask.desc.includes(tsk.desc)) {
                mergedTask.desc += ", ".concat(tsk.desc);
              }
            });

            // Generate final list object
            Object.values(supportedSubtasksFilter).forEach(function (v) {
              var desc = v.desc ? "(".concat(v.desc, ")") : '';
              var key = "".concat(v.taskKey, " ").concat((0, _logger.chalk)().grey(desc));
              supportedSubtasks[key] = {
                taskKey: v.taskKey };

            });

            subTasks = Object.keys(supportedSubtasks);if (!
            subTasks.length) {_context3.next = 38;break;}_context3.next = 34;return (
              (0, _prompt.inquirerPrompt)({
                type: 'list',
                name: 'subCommand',
                message: message,
                choices: subTasks }));case 34:_yield$inquirerPrompt2 = _context3.sent;subCommand = _yield$inquirerPrompt2.subCommand;

            if (isAutoComplete) {
              task = supportedSubtasks[subCommand].taskKey;
              c.command = task.split(' ')[0];
              c.subCommand = task.split(' ')[1];
              if (c.subCommand) {
                task = "".concat(c.command, " ").concat(c.subCommand);
              } else {
                task = "".concat(c.command);
              }
            } else {
              c.subCommand = supportedSubtasks[subCommand].taskKey;
              task = "".concat(c.command, " ").concat(c.subCommand);
            }


            suitableEngines = REGISTERED_ENGINES.
            filter(function (engine) {return (0, _engineManager.hasEngineTask)(task, engine.tasks, c.paths.project.configExists);});case 38:if (!



            CUSTOM_TASKS[task]) {_context3.next = 42;break;}
            // Custom tasks are executed by core engine
            (0, _logger.logInfo)("Running custom task ".concat(task));_context3.next = 51;break;case 42:if (
            suitableEngines.length) {_context3.next = 51;break;}if (
            c.runtime.hasAllEnginesRegistered) {_context3.next = 47;break;}_context3.next = 46;return (

              (0, _engineManager.registerAllPlatformEngines)(c));case 46:return _context3.abrupt("return",
            findSuitableTask(c));case 47:


            (0, _logger.logError)("could not find suitable task for ".concat((0, _logger.chalk)().white(c.command)));
            c.command = null;
            c.subCommand = null;return _context3.abrupt("return",
            findSuitableTask(c));case 51:if (!(

            !c.platform || c.platform === true)) {_context3.next = 54;break;}_context3.next = 54;return (
              _selectPlatform(c, suitableEngines, task));case 54:

            c.runtime.engine = (0, _engineManager.getEngineRunner)(c, task, CUSTOM_TASKS, false);
            // Cover scenarios of -p xxxxxxxxx
            if (c.runtime.engine) {_context3.next = 59;break;}_context3.next = 58;return (
              _selectPlatform(c, suitableEngines, task));case 58:
            c.runtime.engine = (0, _engineManager.getEngineRunner)(c, task, CUSTOM_TASKS);case 59:


            (0, _logger.logInfo)("Current Engine: ".concat((0, _logger.chalk)().bold.white(
            c.runtime.engine.config.id), " path: ").concat(
            (0, _logger.chalk)().grey(c.runtime.engine.rootPath)));
            customTask = CUSTOM_TASKS[task];if (!
            customTask) {_context3.next = 63;break;}return _context3.abrupt("return", customTask);case 63:_context3.next = 67;break;case 65:

            task = specificTask;
            c.runtime.engine = (0, _engineManager.getEngineRunner)(c, task);case 67:

            c.runtime.availablePlatforms = Object.keys(c.runtime.engine.platforms || []);return _context3.abrupt("return",
            (0, _engineManager.getEngineTask)(task, c.runtime.engine.tasks));case 69:case "end":return _context3.stop();}}}, _callee3);}));return function findSuitableTask(_x5, _x6) {return _ref4.apply(this, arguments);};}();exports.findSuitableTask = findSuitableTask;


var _selectPlatform = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c, suitableEngines, task) {var supportedPlatforms, platforms, _yield$inquirerPrompt3, platform;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            supportedPlatforms = {};
            suitableEngines.forEach(function (engine) {
              (0, _engineManager.getEngineTask)(task, engine.tasks).platforms.forEach(function (plat) {
                supportedPlatforms[plat] = true;
              });
            });
            platforms = Object.keys(supportedPlatforms);if (!

            platforms.length) {_context4.next = 9;break;}_context4.next = 6;return (
              (0, _prompt.inquirerPrompt)({
                type: 'list',
                name: 'platform',
                message: "Pick a platform for ".concat(task),
                choices: platforms }));case 6:_yield$inquirerPrompt3 = _context4.sent;platform = _yield$inquirerPrompt3.platform;

            c.platform = platform;case 9:case "end":return _context4.stop();}}}, _callee4);}));return function _selectPlatform(_x7, _x8, _x9) {return _ref5.apply(this, arguments);};}();




var _executePipe = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c, task, phase) {return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:return _context5.abrupt("return", (0, _buildHooks.executePipe)(c, "".concat(task.split(' ').join(':'), ":").concat(phase)));case 1:case "end":return _context5.stop();}}}, _callee5);}));return function _executePipe(_x10, _x11, _x12) {return _ref6.apply(this, arguments);};}();

var TASK_LIMIT = 20;

var executeTask = /*#__PURE__*/function () {var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(c, task, parentTask, originTask, isFirstTask) {var pt, prt;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
            pt = parentTask ? "=> [".concat(parentTask, "] ") : '';
            c._currentTask = task;
            (0, _logger.logInitTask)("".concat(pt, "=> [").concat((0, _logger.chalk)().bold.rgb(170, 106, 170)(task), "]"));

            if (!executedTasks[task]) executedTasks[task] = 0;if (!(
            executedTasks[task] > TASK_LIMIT)) {_context6.next = 6;break;}return _context6.abrupt("return",
            Promise.reject("You reached maximum amount of executions per one task (".concat(TASK_LIMIT, ") task: ").concat(task, ".\nThis is to warn you ended up in task loop.\n(").concat(

            task, " calls same or another task which calls ").concat(task, " again)\nbut issue migh not be necessarily with this task\n\nTo avoid that test your task code against parentTask and avoid executing same task X from within task X")));case 6:_context6.next = 8;return (




              executeEngineTask(
              c, task, parentTask, originTask,
              (0, _engineManager.getEngineRunner)(c, task, CUSTOM_TASKS).tasks,
              isFirstTask));case 8:

            // await getEngineRunner(c, task, CUSTOM_TASKS).executeTask(c, task, parentTask, originTask, isFirstTask);
            executedTasks[task]++;

            c._currentTask = parentTask;
            prt = parentTask ? "<= [".concat((0, _logger.chalk)().rgb(170, 106, 170)(parentTask), "] ") : '';
            (0, _logger.logExitTask)("".concat(prt, "<= ").concat(task));case 12:case "end":return _context6.stop();}}}, _callee6);}));return function executeTask(_x13, _x14, _x15, _x16, _x17) {return _ref7.apply(this, arguments);};}();exports.executeTask = executeTask;


var executeOrSkipTask = /*#__PURE__*/function () {var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(c, task, parentTask, originTask) {return regeneratorRuntime.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:if (
            c.program.only) {_context7.next = 2;break;}return _context7.abrupt("return",
            executeTask(c, task, parentTask, originTask));case 2:return _context7.abrupt("return",


            executeTask(c, _constants.TASK_CONFIGURE_SOFT, parentTask, originTask));case 3:case "end":return _context7.stop();}}}, _callee7);}));return function executeOrSkipTask(_x18, _x19, _x20, _x21) {return _ref8.apply(this, arguments);};}();exports.executeOrSkipTask = executeOrSkipTask;


var ACCEPTED_CONDITIONS = [
'platform',
'target',
'appId',
'scheme'];


var _logSkip = function _logSkip(task) {
  (0, _logger.logInfo)("Original RNV task ".concat((0, _logger.chalk)().white(task), " marked to ignore. SKIPPING..."));
};

var shouldSkipTask = function shouldSkipTask(c, task, originTask) {var _c$buildConfig;
  var tasks = (_c$buildConfig = c.buildConfig) === null || _c$buildConfig === void 0 ? void 0 : _c$buildConfig.tasks;
  c.runtime.platform = c.platform;
  if (!tasks) return;

  if (Array.isArray(tasks)) {
    for (var k = 0; k < tasks.length; k++) {
      var t = tasks[k];
      if (t.name === task) {
        if (t.filter) {var _ret = function () {
            var conditions = t.filter.split('&');
            var conditionsToMatch = conditions.length;
            conditions.forEach(function (con) {
              var conArr = con.split('=');
              if (ACCEPTED_CONDITIONS.includes(conArr[0])) {
                if (c.runtime[conArr[0]] === conArr[1]) {
                  conditionsToMatch--;
                }
              } else {
                (0, _logger.logWarning)("Condition ".concat(con, " not valid. only following keys are valid: ").concat(ACCEPTED_CONDITIONS.join(','), " SKIPPING..."));
              }
            });
            if (conditionsToMatch === 0) {
              if (t.ignore) {
                _logSkip(task);
                return { v: true };
              }
            }}();if (_typeof(_ret) === "object") return _ret.v;
        } else if (t.ignore) {
          _logSkip(task);
          return true;
        }
      }
    }
  } else {var _tasks$task, _tasks$task$platform, _tasks$task$platform$, _tasks$originTask, _tasks$originTask$pla, _tasks$originTask$pla2;
    var ignoreTask = (_tasks$task = tasks[task]) === null || _tasks$task === void 0 ? void 0 : (_tasks$task$platform = _tasks$task.platform) === null || _tasks$task$platform === void 0 ? void 0 : (_tasks$task$platform$ = _tasks$task$platform[c.platform]) === null || _tasks$task$platform$ === void 0 ? void 0 : _tasks$task$platform$.ignore;
    if (ignoreTask) {
      _logSkip(task);
      return true;
    }
    var ignoreTasks = ((_tasks$originTask = tasks[originTask]) === null || _tasks$originTask === void 0 ? void 0 : (_tasks$originTask$pla = _tasks$originTask.platform) === null || _tasks$originTask$pla === void 0 ? void 0 : (_tasks$originTask$pla2 = _tasks$originTask$pla[c.platform]) === null || _tasks$originTask$pla2 === void 0 ? void 0 : _tasks$originTask$pla2.ignoreTasks) || [];
    if (ignoreTasks.includes(task)) {
      (0, _logger.logInfo)("Task ".concat(task, " marked to skip during rnv ").concat(originTask, ". SKIPPING..."));
      return true;
    }
  }

  return false;
};exports.shouldSkipTask = shouldSkipTask;

var executeEngineTask = /*#__PURE__*/function () {var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(c, task, parentTask, originTask, tasks, isFirstTask) {var needsHelp, t, inOnlyMode, doPipe;return regeneratorRuntime.wrap(function _callee8$(_context8) {while (1) {switch (_context8.prev = _context8.next) {case 0:
            needsHelp = Object.prototype.hasOwnProperty.call(c.program, 'help');

            t = (0, _engineManager.getEngineTask)(task, tasks, CUSTOM_TASKS);if (!(

            needsHelp && !parentTask)) {_context8.next = 10;break;}
            (0, _logger.logRaw)("\n=======================================================\nINTERACTIVE HELP FOR TASK: ".concat(

            (0, _logger.chalk)().green(t.task), "\n\nDescription: ").concat(

            t.description, "\n\nOptions:\n\n").concat(



            t.params.map(function (v) {
              var option = v.shortcut ? "`-".concat(v.shortcut, "`, ") : '';
              return "".concat(option, "`--").concat(v.key, "` - ").concat(v.description);
            }).join('\n'), "\n\n  "));if (!


            t.fnHelp) {_context8.next = 7;break;}_context8.next = 7;return (
              t.fnHelp(c, parentTask, originTask));case 7:_context8.next = 9;return (


              (0, _prompt.pressAnyKeyToContinue)());case 9:
            (0, _logger.logRaw)("\n=======================================================");case 10:if (!(


            !t.isGlobalScope && isFirstTask)) {_context8.next = 14;break;}if (!
            c.files.project["package"]) {_context8.next = 14;break;}_context8.next = 14;return (

              (0, _npmUtils.checkIfProjectAndNodeModulesExists)(c));case 14:


            if (isFirstTask) {
              c.runtime.forceBuildHookRebuild = t.forceBuildHookRebuild;
            }
            inOnlyMode = c.program.only;
            doPipe = !t.isGlobalScope && (!inOnlyMode || inOnlyMode && isFirstTask);if (!
            doPipe) {_context8.next = 20;break;}_context8.next = 20;return _executePipe(c, task, 'before');case 20:_context8.next = 22;return (
              t.fn(c, parentTask, originTask));case 22:if (!
            doPipe) {_context8.next = 25;break;}_context8.next = 25;return _executePipe(c, task, 'after');case 25:case "end":return _context8.stop();}}}, _callee8);}));return function executeEngineTask(_x22, _x23, _x24, _x25, _x26, _x27) {return _ref9.apply(this, arguments);};}();exports.executeEngineTask = executeEngineTask;
//# sourceMappingURL=index.js.map