"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.taskRnvAppConfigure = exports["default"] = void 0;var _path = _interopRequireDefault(require("path"));
var _inquirer = _interopRequireDefault(require("inquirer"));
var _configManager = require("../../core/configManager");
var _runtimeManager = require("../../core/runtimeManager");
var _constants = require("../../core/constants");
var _fileutils = require("../../core/systemManager/fileutils");





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








var _prompt = require("../../cli/prompt");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": 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 _loadAppConfigIDfromDir = function _loadAppConfigIDfromDir(dirName, appConfigsDir) {
  (0, _logger.logDebug)("_loadAppConfigIDfromDir:".concat(dirName, ":").concat(appConfigsDir), (0, _logger.chalk)().grey);
  var filePath = _path["default"].join(appConfigsDir, 'renative.json');
  if ((0, _fileutils.fsExistsSync)(filePath)) {
    try {
      var renativeConf = JSON.parse((0, _fileutils.fsReadFileSync)(filePath));
      return { dir: dirName, id: renativeConf.id };
    } catch (e) {
      (0, _logger.logError)("File ".concat(filePath, " is MALFORMED:\n").concat(e));
    }
  }
  return { dir: dirName, id: null };
};

var _askUserAboutConfigs = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c, dir, id, basePath) {var _yield$inquirer$promp, choice, conf, filePath, fileContents;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
            (0, _logger.logTask)('_askUserAboutConfigs');
            (0, _logger.logWarning)("AppConfig error - It seems you have a mismatch between appConfig folder name (".concat(

            dir, ") and the id defined in renative.json (").concat(
            id, "). They must match."));if (!(

            c.program.ci === true)) {_context.next = 4;break;}throw (
              new Error(
              'You cannot continue if you set --ci flag. please fix above error first'));case 4:_context.next = 6;return (


              _inquirer["default"].prompt({
                type: 'list',
                name: 'choice',
                message: 'You must choose what you want to keep',
                choices: [
                // {
                //     name: `Keep ID from renative.json (${id}) and rename the folder (${dir} -> ${id})`,
                //     value: 'keepID'
                // },
                {
                  name: "Keep folder name (".concat(dir, ") and rename the ID from renative.json (").concat(id, " -> ").concat(dir, ")"),
                  value: 'keepFolder' },

                new _inquirer["default"].Separator(),
                {
                  name: "I'll do it manually",
                  value: 'manually' }] }));case 6:_yield$inquirer$promp = _context.sent;choice = _yield$inquirer$promp.choice;if (!(




            choice === 'manually')) {_context.next = 10;break;}throw (
              new Error('Please do the changes and rerun the command'));case 10:


            conf = { id: id, dir: dir };

            if (choice === 'keepID') {
              conf.dir = _path["default"].join(basePath, id);
              (0, _fileutils.fsRenameSync)(_path["default"].join(basePath, dir), conf.dir);
            }

            if (choice === 'keepFolder') {
              filePath = _path["default"].join(basePath, dir, 'renative.json');
              fileContents = JSON.parse((0, _fileutils.fsReadFileSync)(filePath));
              fileContents.id = dir;
              conf.id = dir;

              (0, _fileutils.writeFileSync)(filePath, fileContents);
            }return _context.abrupt("return",

            conf);case 14:case "end":return _context.stop();}}}, _callee);}));return function _askUserAboutConfigs(_x, _x2, _x3, _x4) {return _ref.apply(this, arguments);};}();


/* eslint-disable no-await-in-loop */
var matchAppConfigID = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, appConfigID) {var _c$paths$project, appConfigsDirs, appConfigsDirNames, acIndex, conf, _conf, dir, id;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('matchAppConfigID', "appId:".concat(appConfigID));if (

            appConfigID) {_context2.next = 3;break;}return _context2.abrupt("return", false);case 3:_c$paths$project =

            c.paths.project, appConfigsDirs = _c$paths$project.appConfigsDirs, appConfigsDirNames = _c$paths$project.appConfigsDirNames;

            acIndex = appConfigsDirNames.indexOf(appConfigID);if (!(
            acIndex !== -1)) {_context2.next = 13;break;}
            conf = _loadAppConfigIDfromDir(appConfigID, appConfigsDirs[acIndex]);_conf =
            conf, dir = _conf.dir, id = _conf.id;if (!(
            id !== dir)) {_context2.next = 12;break;}_context2.next = 11;return (
              _askUserAboutConfigs(
              c,
              conf.dir,
              conf.id,
              _path["default"].join(appConfigsDirs[acIndex], '..')));case 11:conf = _context2.sent;case 12:return _context2.abrupt("return",




            conf.id);case 13:return _context2.abrupt("return",

            false);case 14:case "end":return _context2.stop();}}}, _callee2);}));return function matchAppConfigID(_x5, _x6) {return _ref2.apply(this, arguments);};}();


var _findAndSwitchAppConfigDir = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c) {var appConfigsDirNames, _yield$inquirerPrompt, conf;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
            (0, _logger.logTask)('_findAndSwitchAppConfigDir');
            appConfigsDirNames = c.paths.project.appConfigsDirNames;if (!
            appConfigsDirNames.length) {_context3.next = 14;break;}if (!(
            appConfigsDirNames.length === 1)) {_context3.next = 7;break;}
            // we have only one, skip the question
            (0, _logger.logInfo)("Found only one app config available. Will use ".concat(
            (0, _logger.chalk)().white(
            appConfigsDirNames[0])));


            _setAppId(c, appConfigsDirNames[0]);return _context3.abrupt("return",
            true);case 7:_context3.next = 9;return (


              (0, _prompt.inquirerPrompt)({
                name: 'conf',
                type: 'list',
                message: 'Which one would you like to pick?',
                choices: appConfigsDirNames,
                pageSize: 50,
                logMessage: 'ReNative found multiple existing appConfigs' }));case 9:_yield$inquirerPrompt = _context3.sent;conf = _yield$inquirerPrompt.conf;if (!


            conf) {_context3.next = 14;break;}
            _setAppId(c, conf);return _context3.abrupt("return",
            true);case 14:return _context3.abrupt("return",



            false);case 15:case "end":return _context3.stop();}}}, _callee3);}));return function _findAndSwitchAppConfigDir(_x7) {return _ref3.apply(this, arguments);};}();


var _setAppId = function _setAppId(c, appId) {var _c$files$project, _c$files$project$conf, _c$files$project$conf2;
  var currentAppConfigId = (_c$files$project = c.files.project) === null || _c$files$project === void 0 ? void 0 : (_c$files$project$conf = _c$files$project.configLocal) === null || _c$files$project$conf === void 0 ? void 0 : (_c$files$project$conf2 = _c$files$project$conf._meta) === null || _c$files$project$conf2 === void 0 ? void 0 : _c$files$project$conf2.currentAppConfigId;

  (0, _logger.logTask)('_setAppId', "appId:".concat(appId, " runtime.appId:").concat(c.runtime.appId, " _meta.appId:").concat(currentAppConfigId));
  c.runtime.appId = appId || c.runtime.appId || currentAppConfigId;
  c.runtime.appDir = _path["default"].join(c.paths.project.builds.dir, "".concat(c.runtime.appId, "_").concat(c.platform));
};

var taskRnvAppConfigure = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var _c$buildConfig, _c$buildConfig$paths;var appConfigsDirsExt, hasAppConfig, aid, _hasAppConfig;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            (0, _logger.logTask)('taskRnvAppConfigure');

            c.paths.project.appConfigsDirNames = (0, _configManager.listAppConfigsFoldersSync)(c, true);
            c.paths.project.appConfigsDirNames.forEach(function (dirName) {
              c.paths.project.appConfigsDirs.push(_path["default"].join(c.paths.project.appConfigsDir, dirName));
            });

            appConfigsDirsExt = (_c$buildConfig = c.buildConfig) === null || _c$buildConfig === void 0 ? void 0 : (_c$buildConfig$paths = _c$buildConfig.paths) === null || _c$buildConfig$paths === void 0 ? void 0 : _c$buildConfig$paths.appConfigsDirs;
            if (appConfigsDirsExt) {
              appConfigsDirsExt.forEach(function (apePath) {
                var appConfigsExt = (0, _configManager.listAppConfigsFoldersSync)(c, true, apePath);
                appConfigsExt.forEach(function (appExtName) {
                  c.paths.project.appConfigsDirNames.push(appExtName);
                  c.paths.project.appConfigsDirs.push(_path["default"].join(apePath, appExtName));
                });
              });
            }


            // Reset appId if appConfig no longer exists but renative.local.json still has reference to it
            if (!c.paths.project.appConfigsDirNames.includes(c.runtime.appId)) {
              c.runtime.appId = null;
            }if (!(

            c.program.appConfigID === true || !c.program.appConfigID && !c.runtime.appId)) {_context4.next = 14;break;}_context4.next = 9;return (
              _findAndSwitchAppConfigDir(c));case 9:hasAppConfig = _context4.sent;if (
            hasAppConfig) {_context4.next = 12;break;}return _context4.abrupt("return",

            Promise.reject('No app configs found for this project'));case 12:_context4.next = 26;break;case 14:if (!

            c.program.appConfigID) {_context4.next = 26;break;}_context4.next = 17;return (
              matchAppConfigID(c, c.program.appConfigID));case 17:aid = _context4.sent;if (
            aid) {_context4.next = 25;break;}
            (0, _logger.logWarning)("Cannot find app config ".concat((0, _logger.chalk)().white(c.program.appConfigID)));_context4.next = 22;return (
              _findAndSwitchAppConfigDir(c));case 22:_hasAppConfig = _context4.sent;if (
            _hasAppConfig) {_context4.next = 25;break;}return _context4.abrupt("return",

            Promise.reject('No app configs found for this project'));case 25:


            _setAppId(c, aid);case 26:


            // Generate true path to appConfig (ensure external appConfigsDirs are included)
            c.runtime.appConfigDir = c.paths.project.appConfigsDirs[
            c.paths.project.appConfigsDirNames.indexOf(c.runtime.appId)];_context4.next = 29;return (

              (0, _runtimeManager.updateRenativeConfigs)(c));case 29:
            (0, _logger.logAppInfo)(c);return _context4.abrupt("return",

            true);case 31:case "end":return _context4.stop();}}}, _callee4);}));return function taskRnvAppConfigure(_x8) {return _ref4.apply(this, arguments);};}();exports.taskRnvAppConfigure = taskRnvAppConfigure;var _default =


{
  description: 'Configure project with specific appConfig',
  fn: taskRnvAppConfigure,
  task: _constants.TASK_APP_CONFIGURE,
  params: _constants.PARAMS.withBase(_constants.PARAMS.withConfigure()),
  platforms: [] };exports["default"] = _default;
//# sourceMappingURL=task.rnv.app.configure.js.map