"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.listAppleDevices = exports.launchAppleSimulator = exports.getAppleDevices = void 0;var _inquirer = _interopRequireDefault(require("inquirer"));
var _child_process = _interopRequireDefault(require("child_process"));
var _logger = require("../../systemManager/logger");
var _constants = require("../../constants");
var _exec = require("../../systemManager/exec");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 _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 ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);enumerableOnly && (symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;})), keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = null != arguments[i] ? arguments[i] : {};i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {_defineProperty(target, key, source[key]);}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return 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 getAppleDevices = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(
  c,
  ignoreDevices,
  ignoreSimulators) {var platform, skipTargetCheck, devicesAndSims, isXcode13, simctl, availableSims, parseFunction, devicesArr, simulatorsArr, allDevices;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:

            platform = c.platform;

            (0, _logger.logTask)('getAppleDevices', "ignoreDevices:".concat(ignoreDevices, " ignoreSimulators").concat(ignoreSimulators));


            skipTargetCheck =
            c.program.skipTargetCheck;


            isXcode13 = false;_context.prev = 4;

            // xcode >= 13
            isXcode13 = true;_context.next = 8;return (
              (0, _exec.executeAsync)('xcrun xctrace list devices'));case 8:devicesAndSims = _context.sent;_context.next = 16;break;case 11:_context.prev = 11;_context.t0 = _context["catch"](4);_context.next = 15;return (


              (0, _exec.executeAsync)('xcrun instruments -s'));case 15:devicesAndSims = _context.sent;case 16:_context.t1 =

            JSON;_context.next = 19;return (0, _exec.executeAsync)('xcrun simctl list --json');case 19:_context.t2 = _context.sent;simctl = _context.t1.parse.call(_context.t1, _context.t2);
            availableSims = [];
            Object.keys(simctl.devices).forEach(function (runtime) {
              (0, _logger.logDebug)('runtime', runtime);
              simctl.devices[runtime].forEach(function (device) {
                if (device.isAvailable) {
                  availableSims.push(_objectSpread(_objectSpread({},
                  device), {}, {
                    version: runtime.split('.').pop() }));

                }
              });
            });

            parseFunction = _parseIOSDevicesList;
            if (isXcode13) {
              parseFunction = _parseNewIOSDevicesList;
            }
            devicesArr = parseFunction(
            devicesAndSims,
            platform,
            ignoreDevices,
            ignoreSimulators);


            simulatorsArr = _parseIOSDevicesList(
            availableSims,
            platform,
            ignoreDevices,
            ignoreSimulators);

            allDevices = [].concat(_toConsumableArray(devicesArr), _toConsumableArray(simulatorsArr));

            if (!skipTargetCheck) {
              // filter watches
              allDevices = allDevices.filter(function (d) {var _d$version;return !((_d$version = d.version) !== null && _d$version !== void 0 && _d$version.includes('watchOS'));});
              // filter other platforms
              allDevices = allDevices.filter(function (d) {var _d$icon, _d$icon2, _d$icon3;
                if (
                platform === _constants.IOS && (
                (_d$icon = d.icon) !== null && _d$icon !== void 0 && _d$icon.includes('Phone') || (_d$icon2 = d.icon) !== null && _d$icon2 !== void 0 && _d$icon2.includes('Tablet')))
                {return true;}
                if (platform === _constants.TVOS && (_d$icon3 = d.icon) !== null && _d$icon3 !== void 0 && _d$icon3.includes('TV')) return true;
                return false;
              });
            }return _context.abrupt("return",
            allDevices);case 30:case "end":return _context.stop();}}}, _callee, null, [[4, 11]]);}));return function getAppleDevices(_x, _x2, _x3) {return _ref.apply(this, arguments);};}();exports.getAppleDevices = getAppleDevices;


var _parseNewIOSDevicesList = function _parseNewIOSDevicesList(
rawDevices,
platform)

{var ignoreDevices = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  var devices = [];
  if (ignoreDevices) return devices;
  var decideIcon = function decideIcon(device) {
    var name = device.name,isDevice = device.isDevice;
    switch (platform) {
      case _constants.IOS:
        if (
        name.includes('iPhone') ||
        name.includes('iPad') ||
        name.includes('iPod'))
        {
          var icon = 'Phone 📱';
          if (name.includes('iPad')) icon = 'Tablet 💊';
          return icon;
        }
        return null;
      case _constants.TVOS:
        if (
        name.includes('TV') &&
        !name.includes('iPhone') &&
        !name.includes('iPad'))
        {
          return 'TV 📺';
        }
        return null;
      default:
        if (isDevice) {
          return 'Apple Device';
        }
        return null;}

  };
  var lines = rawDevices.split('\n');
  var devicesOnly = lines.slice(1, lines.indexOf(''));
  devicesOnly.forEach(function (device) {
    var udid = device.match(/\(([^()]*)\)$/)[1];
    var name = device.split(' (').slice(0, -1).join(' (');
    var icon = decideIcon({ name: name, isDevice: true });
    devices.push({
      udid: udid,
      name: name,
      icon: icon,
      isDevice: true });

  });

  return devices;
};

var _parseIOSDevicesList = function _parseIOSDevicesList(
rawDevices,
platform)


{var ignoreDevices = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;var ignoreSimulators = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  var devices = [];
  var decideIcon = function decideIcon(device) {
    var name = device.name,isDevice = device.isDevice;
    switch (platform) {
      case _constants.IOS:
        if (
        name.includes('iPhone') ||
        name.includes('iPad') ||
        name.includes('iPod'))
        {
          var icon = 'Phone 📱';
          if (name.includes('iPad')) icon = 'Tablet 💊';
          return icon;
        }
        return null;
      case _constants.TVOS:
        if (
        name.includes('TV') &&
        !name.includes('iPhone') &&
        !name.includes('iPad'))
        {
          return 'TV 📺';
        }
        return null;
      default:
        if (isDevice) {
          return 'Apple Device';
        }
        return null;}

  };
  if (typeof rawDevices === 'string' && !ignoreDevices) {
    rawDevices.split('\n').forEach(function (line) {
      var s1 = line.match(/\[.*?\]/);
      var s2 = line.match(/\(.*?\)/g);
      // const s3 = line.substring(0, line.indexOf('(') - 1);
      var s4 = line.substring(0, line.indexOf('[') - 1);
      var isSim = false;
      if (s2 && s1) {
        if (s2[s2.length - 1] === '(Simulator)') {
          isSim = true;
          s2.pop();
        }
        var version = s2.pop();
        var name = "".concat(s4.substring(0, s4.lastIndexOf('(') - 1));
        name = name || 'undefined';
        var udid = s1[0].replace(/\[|\]/g, '');
        var isDevice = !isSim;
        if (!isDevice) return; // only take care of devices.

        if (!ignoreDevices) {
          var device = { udid: udid, name: name, version: version, isDevice: isDevice };
          devices.push(_objectSpread(_objectSpread({}, device), {}, { icon: decideIcon(device) }));
        }
      }
    });
  } else if (_typeof(rawDevices) === 'object' && !ignoreSimulators) {
    rawDevices.forEach(function (d) {
      var name = d.name,udid = d.udid,version = d.version;
      var device = {
        name: name,
        udid: udid,
        isDevice: false,
        version: version };

      devices.push(_objectSpread(_objectSpread({}, device), {}, { icon: decideIcon(device) }));
    });
  }

  return devices;
};

var launchAppleSimulator = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, target) {var devicesArr, selectedDevice, i, devices, _yield$inquirer$promp, sim;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('launchAppleSimulator', "".concat(target));_context2.next = 3;return (

              getAppleDevices(c, true));case 3:devicesArr = _context2.sent;


            for (i = 0; i < devicesArr.length; i++) {
              if (devicesArr[i].name === target) {
                selectedDevice = devicesArr[i];
              }
            }if (!
            selectedDevice) {_context2.next = 9;break;}_context2.next = 8;return (
              _launchSimulator(selectedDevice));case 8:return _context2.abrupt("return",
            selectedDevice.name);case 9:


            (0, _logger.logWarning)("Your specified simulator target ".concat(
            (0, _logger.chalk)().white(target), " doesn't exists"));

            devices = devicesArr.map(function (v) {return {
                name: "".concat(v.name, " | ").concat(v.icon, " | v: ").concat((0, _logger.chalk)().green(
                v.version), " | udid: ").concat(
                (0, _logger.chalk)().grey(v.udid)).concat(
                v.isDevice ? (0, _logger.chalk)().red(' (device)') : ''),

                value: v };});_context2.next = 13;return (


              _inquirer["default"].prompt({
                name: 'sim',
                message: 'Select the simulator you want to launch',
                type: 'list',
                choices: devices }));case 13:_yield$inquirer$promp = _context2.sent;sim = _yield$inquirer$promp.sim;if (!


            sim) {_context2.next = 19;break;}_context2.next = 18;return (
              _launchSimulator(sim));case 18:return _context2.abrupt("return",
            sim.name);case 19:return _context2.abrupt("return",

            Promise.reject('Action canceled!'));case 20:case "end":return _context2.stop();}}}, _callee2);}));return function launchAppleSimulator(_x4, _x5) {return _ref2.apply(this, arguments);};}();exports.launchAppleSimulator = launchAppleSimulator;


var _launchSimulator = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(selectedDevice) {return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
            try {
              _child_process["default"].spawnSync('xcrun', [
              'simctl',
              'boot',
              selectedDevice.udid]);

            } catch (e) {
              // instruments always fail with 255 because it expects more arguments,
              // but we want it to only launch the simulator
            }return _context3.abrupt("return",

            true);case 2:case "end":return _context3.stop();}}}, _callee3);}));return function _launchSimulator(_x6) {return _ref3.apply(this, arguments);};}();


var listAppleDevices = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var platform, devicesArr, devicesString;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            (0, _logger.logTask)('listAppleDevices');
            platform = c.platform;_context4.next = 4;return (
              getAppleDevices(c));case 4:devicesArr = _context4.sent;
            devicesString = '';
            devicesArr.forEach(function (v, i) {
              devicesString += " [".concat(i + 1, "]> ").concat((0, _logger.chalk)().bold(v.name), " | ").concat(
              v.icon, " | v: ").concat(
              (0, _logger.chalk)().green(v.version), " | udid: ").concat((0, _logger.chalk)().grey(v.udid)).concat(
              v.isDevice ? (0, _logger.chalk)().red(' (device)') : '', "\n");

            });

            (0, _logger.logToSummary)("".concat(platform, " Targets:\n\n").concat(devicesString));case 8:case "end":return _context4.stop();}}}, _callee4);}));return function listAppleDevices(_x7) {return _ref4.apply(this, arguments);};}();exports.listAppleDevices = listAppleDevices;
//# sourceMappingURL=apple.js.map