"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.updateProjectPlatforms = exports.logErrorPlatform = exports.isPlatformSupportedSync = exports.isPlatformSupported = exports.isPlatformActive = exports.generatePlatformChoices = exports.ejectPlatform = exports.createPlatformBuild = exports.copySharedPlatforms = exports.cleanPlatformBuild = void 0;var _path = _interopRequireDefault(require("path"));
var _logger = require("../systemManager/logger");
var _prompt = require("../../cli/prompt");
var _fileutils = require("../systemManager/fileutils");




var _installer = require("../sdkManager/installer");
var _common = require("../common");
var _constants = require("../constants");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _toConsumableArray(arr) {return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();}function _nonIterableSpread() {throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _iterableToArray(iter) {if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);}function _arrayWithoutHoles(arr) {if (Array.isArray(arr)) return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}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 logErrorPlatform = function logErrorPlatform(c) {
  (0, _logger.logError)("Platform: ".concat(
  (0, _logger.chalk)().white(
  c.platform), " doesn't support command: ").concat(
  (0, _logger.chalk)().white(c.command)),
  true // kill it if we're not supporting this
  );
  return false;
};exports.logErrorPlatform = logErrorPlatform;

var updateProjectPlatforms = function updateProjectPlatforms(c, platforms) {
  var
  config =
  c.paths.project.config;
  var currentConfig = c.files.project.config;
  currentConfig.defaults = currentConfig.defaults || {};
  currentConfig.defaults.supportedPlatforms = platforms;
  (0, _fileutils.writeFileSync)(config, currentConfig);
};exports.updateProjectPlatforms = updateProjectPlatforms;


var generatePlatformChoices = function generatePlatformChoices(c) {
  var options = c.runtime.supportedPlatforms.map(function (v) {var _v$engine, _v$engine$config;return {
      name: "".concat(v.platform, " - ").concat(v.isConnected ? (0, _logger.chalk)().green('(connected)') : (0, _logger.chalk)().yellow('(ejected)'), " [").concat((0, _logger.chalk)().cyan((_v$engine = v.engine) === null || _v$engine === void 0 ? void 0 : (_v$engine$config = _v$engine.config) === null || _v$engine$config === void 0 ? void 0 : _v$engine$config.id), "]"),
      value: v.platform,
      isConnected: v.isConnected };});

  return options;
};exports.generatePlatformChoices = generatePlatformChoices;

var cleanPlatformBuild = function cleanPlatformBuild(c, platform) {return new Promise(function (resolve) {
    (0, _logger.logTask)('cleanPlatformBuild');

    var cleanTasks = [];

    if (platform === 'all') {
      Object.keys(c.buildConfig.platforms).forEach(function (k) {
        if (isPlatformSupportedSync(c, k)) {
          var pPath = _path["default"].join(
          c.paths.project.builds.dir, "".concat(
          c.runtime.appId, "_").concat(k));

          cleanTasks.push((0, _fileutils.cleanFolder)(pPath));
        }
      });
    } else if (isPlatformSupportedSync(c, platform)) {
      var pPath = _path["default"].join(
      c.paths.project.builds.dir, "".concat(
      c.runtime.appId, "_").concat(platform));

      cleanTasks.push((0, _fileutils.cleanFolder)(pPath));
    }

    Promise.all(cleanTasks).then(function () {
      resolve();
    });
  });};exports.cleanPlatformBuild = cleanPlatformBuild;

var createPlatformBuild = function createPlatformBuild(c, platform) {return new Promise(function (resolve, reject) {
    (0, _logger.logTask)('createPlatformBuild');

    if (!isPlatformSupportedSync(c, platform, null, reject)) return;

    var pPath = _path["default"].join(
    c.paths.project.builds.dir, "".concat(
    c.runtime.appId, "_").concat(platform));

    var ptPath = _path["default"].join(
    c.paths.project.platformTemplatesDirs[platform], "".concat(
    platform));


    (0, _fileutils.copyFolderContentsRecursiveSync)(ptPath, pPath, false, [
    _path["default"].join(ptPath, '_privateConfig')],
    false, {}, (0, _common.getTimestampPathsConfig)(c, platform), c);

    resolve();
  });};exports.createPlatformBuild = createPlatformBuild;

var isPlatformSupported = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c) {var _c$files$project$conf, _c$files$project$conf2;var isGlobalScope,platformsAsObj,opts,_yield$inquirerPrompt,platform,configuredPlatforms,_yield$inquirerPrompt2,confirm,newPlatforms,_args = arguments;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:isGlobalScope = _args.length > 1 && _args[1] !== undefined ? _args[1] : false;
            (0, _logger.logTask)('isPlatformSupported');if (!(


            c.platform && c.platform !== true && isGlobalScope)) {_context.next = 4;break;}return _context.abrupt("return",
            c.platform);case 4:



            if (isGlobalScope) {
              platformsAsObj = _constants.SUPPORTED_PLATFORMS;
            } else {
              platformsAsObj = c.buildConfig ? c.buildConfig.platforms : c.supportedPlatforms;
            }

            if (!platformsAsObj) platformsAsObj = c.runtime.availablePlatforms;
            opts = (0, _prompt.generateOptions)(platformsAsObj);if (!(


            !c.platform ||
            c.platform === true ||
            !c.runtime.availablePlatforms.includes(c.platform))) {_context.next = 13;break;}_context.next = 10;return (

              (0, _prompt.inquirerPrompt)({
                name: 'platform',
                type: 'list',
                message: 'Pick one of available platforms',
                choices: opts.keysAsArray,
                logMessage: 'You need to specify platform' }));case 10:_yield$inquirerPrompt = _context.sent;platform = _yield$inquirerPrompt.platform;


            c.platform = platform;case 13:


            configuredPlatforms = (_c$files$project$conf = c.files.project.config) === null || _c$files$project$conf === void 0 ? void 0 : (_c$files$project$conf2 = _c$files$project$conf.defaults) === null || _c$files$project$conf2 === void 0 ? void 0 : _c$files$project$conf2.supportedPlatforms;if (!(


            Array.isArray(configuredPlatforms) &&
            !configuredPlatforms.includes(c.platform))) {_context.next = 26;break;}_context.next = 17;return (

              (0, _prompt.inquirerPrompt)({
                type: 'confirm',
                message: "Platform ".concat(
                c.platform, " is not supported by your project. Would you like to enable it?") }));case 17:_yield$inquirerPrompt2 = _context.sent;confirm = _yield$inquirerPrompt2.confirm;if (!



            confirm) {_context.next = 25;break;}
            newPlatforms = [].concat(_toConsumableArray(configuredPlatforms), [c.platform]);
            updateProjectPlatforms(c, newPlatforms);
            c.buildConfig.defaults.supportedPlatforms = newPlatforms;
            // await configureEntryPoints(c);
            _context.next = 26;break;case 25:throw (
              new Error('User canceled'));case 26:_context.next = 28;return (




              (0, _installer.checkAndConfigureSdks)(c));case 28:return _context.abrupt("return",
            c.platform);case 29:case "end":return _context.stop();}}}, _callee);}));return function isPlatformSupported(_x) {return _ref.apply(this, arguments);};}();exports.isPlatformSupported = isPlatformSupported;


var isPlatformSupportedSync = function isPlatformSupportedSync(c, platform, resolve, reject) {
  if (!platform) {
    if (reject) {
      reject(
      (0, _logger.chalk)().red("You didn't specify platform. make sure you add \"".concat(
      (0, _logger.chalk)().white.bold(
      '-p <PLATFORM>'), "\" option to your command!")));



    }
    return false;
  }
  if (!c.runtime.availablePlatforms.includes(platform)) {
    if (reject) {
      reject(
      (0, _logger.chalk)().red("Platform ".concat(
      platform, " is not supported. Use one of the following: ").concat((0, _logger.chalk)().white(
      c.runtime.availablePlatforms.join(', ')), " .")));



    }
    return false;
  }
  if (resolve) resolve();
  return true;
};exports.isPlatformSupportedSync = isPlatformSupportedSync;

var isPlatformActive = function isPlatformActive(c, platform, resolve) {
  if (!c.buildConfig || !c.buildConfig.platforms) {
    (0, _logger.logError)("Your appConfigFile is not configured properly! check ".concat(
    (0, _logger.chalk)().white(
    c.paths.appConfig.config), " location."));


    if (resolve) resolve();
    return false;
  }
  if (!c.buildConfig.platforms[platform]) {
    (0, _logger.logWarning)("Platform ".concat(
    platform, " not configured for ").concat(c.runtime.appId, ". skipping."));

    if (resolve) resolve();
    return false;
  }
  return true;
};exports.isPlatformActive = isPlatformActive;
var copySharedPlatforms = function copySharedPlatforms(c) {return new Promise(function (resolve) {
    (0, _logger.logTask)('copySharedPlatforms');

    if (c.platform) {
      (0, _fileutils.copyFolderContentsRecursiveSync)(
      _path["default"].resolve(
      c.paths.project.platformTemplatesDirs[c.platform],
      '_shared'),

      (0, _common.getPlatformBuildDir)(c));

    }

    resolve();
  });};exports.copySharedPlatforms = copySharedPlatforms;

var ejectPlatform = function ejectPlatform(c, platform) {
  var engine = c.runtime.enginesByPlatform[platform];
  var destDir = _path["default"].join(c.paths.project.dir, 'platformTemplates', platform);
  var sourcePlatformDir = engine.originalTemplatePlatformsDir;
  (0, _fileutils.copyFolderContentsRecursiveSync)(
  _path["default"].join(sourcePlatformDir, platform),
  destDir);

  // DEPRECATED: only for legacy support
  (0, _fileutils.copyFolderContentsRecursiveSync)(
  _path["default"].join(sourcePlatformDir, '_shared'),
  destDir);

};exports.ejectPlatform = ejectPlatform;
//# sourceMappingURL=index.js.map