"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.resetAdb = exports.listAndroidTargets = exports.launchAndroidSimulator = exports.getAndroidTargets = exports.connectToWifiDevice = exports.composeDevicesString = exports.checkForActiveEmulator = exports.askForNewEmulator = void 0;var _path = _interopRequireDefault(require("path"));
var _child_process = _interopRequireDefault(require("child_process"));
var _inquirer = _interopRequireDefault(require("inquirer"));
var _fileutils = require("../../systemManager/fileutils");
var _exec = require("../../systemManager/exec");
var _common = require("./common");
var _utils = require("../../systemManager/utils");
var _logger = require("../../systemManager/logger");









var _constants = require("../../constants");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}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 _slicedToArray(arr, i) {return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();}function _nonIterableRest() {throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) {var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];if (_i == null) return;var _arr = [];var _n = true;var _d = false;var _s, _e;try {for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"] != null) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}function _arrayWithHoles(arr) {if (Array.isArray(arr)) return arr;}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 CHECK_INTEVAL = 5000;

var currentDeviceProps = {};

var composeDevicesString = function composeDevicesString(devices, returnArray) {
  (0, _logger.logTask)('composeDevicesString', "numDevices:".concat(devices ? devices.length : null));
  var devicesArray = [];
  devices.forEach(function (v, i) {return devicesArray.push(_getDeviceString(v, !returnArray ? i : null));});
  if (returnArray) return devicesArray;
  return "\n".concat(devicesArray.join(''));
};exports.composeDevicesString = composeDevicesString;

var launchAndroidSimulator = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c, target) {var isIndependentThread,newTarget,device,list,devicesString,choices,response,actualTarget,_args = arguments;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:isIndependentThread = _args.length > 2 && _args[2] !== undefined ? _args[2] : false;
            (0, _logger.logTask)(
            'launchAndroidSimulator', "target:".concat(target, " independentThread:").concat(!!isIndependentThread));

            newTarget = target;if (!(
            target === true)) {_context.next = 14;break;}

            device =
            c.program.device;_context.next = 7;return (
              getAndroidTargets(c, false, device, device));case 7:list = _context.sent;

            devicesString = composeDevicesString(list, true);
            choices = devicesString;_context.next = 12;return (
              _inquirer["default"].prompt([
              {
                name: 'chosenEmulator',
                type: 'list',
                message: 'What emulator would you like to start?',
                choices: choices }]));case 12:response = _context.sent;


            newTarget = response.chosenEmulator;case 14:if (!


            newTarget) {_context.next = 20;break;}
            actualTarget = newTarget.name || newTarget;if (!
            isIndependentThread) {_context.next = 19;break;}
            (0, _exec.execCLI)(c, _constants.CLI_ANDROID_EMULATOR, "-avd \"".concat(actualTarget, "\""), {
              detached: isIndependentThread })["catch"](
            function (err) {
              if (err.includes && err.includes('WHPX')) {
                (0, _logger.logWarning)(err);
                return (0, _logger.logError)(
                'It seems you do not have the Windows Hypervisor Platform virtualization enabled. Enter windows features in the Windows search box and select Turn Windows features on or off in the search results. In the Windows Features dialog, enable both Hyper-V and Windows Hypervisor Platform.',
                true);

              }
              (0, _logger.logError)(err);
            });return _context.abrupt("return",
            Promise.resolve());case 19:return _context.abrupt("return",

            (0, _exec.execCLI)(c, _constants.CLI_ANDROID_EMULATOR, "-avd \"".concat(actualTarget, "\""), {
              detached: isIndependentThread }));case 20:return _context.abrupt("return",


            Promise.reject('No simulator -t target name specified!'));case 21:case "end":return _context.stop();}}}, _callee);}));return function launchAndroidSimulator(_x, _x2) {return _ref.apply(this, arguments);};}();exports.launchAndroidSimulator = launchAndroidSimulator;


var listAndroidTargets = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c) {var device, list, devices;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('listAndroidTargets');

            device =
            c.program.device;_context2.next = 4;return (

              resetAdb(c));case 4:_context2.next = 6;return (
              getAndroidTargets(c, false, device, device));case 6:list = _context2.sent;_context2.next = 9;return (
              composeDevicesString(list));case 9:devices = _context2.sent;
            (0, _logger.logToSummary)("Android Targets:\n".concat(devices));
            if (devices.trim() === '') {
              (0, _logger.logToSummary)('Android Targets: No devices found');
            }return _context2.abrupt("return",
            devices);case 13:case "end":return _context2.stop();}}}, _callee2);}));return function listAndroidTargets(_x3) {return _ref2.apply(this, arguments);};}();exports.listAndroidTargets = listAndroidTargets;


var _getDeviceString = function _getDeviceString(device, i) {
  var
  isTV =








  device.isTV,isTablet = device.isTablet,name = device.name,udid = device.udid,isDevice = device.isDevice,isActive = device.isActive,avdConfig = device.avdConfig,isWear = device.isWear,arch = device.arch;
  var deviceIcon = '';
  if (isTablet) deviceIcon = 'Tablet 💊 ';
  if (isTV) deviceIcon = 'TV 📺 ';
  if (isWear) deviceIcon = 'Wear ⌚ ';
  if (!deviceIcon && (udid !== 'unknown' || avdConfig)) {
    deviceIcon = 'Phone 📱 ';
  }

  var deviceString = "".concat((0, _logger.chalk)().white(
  name), " | ").concat(
  deviceIcon, " | arch: ").concat(arch, " | udid: ").concat((0, _logger.chalk)().grey(udid)).concat(
  isDevice ? (0, _logger.chalk)().red(' (device)') : '', " ").concat(
  isActive ? (0, _logger.chalk)().magenta(' (active)') : '');

  if (i === null) {
    return { key: name, name: deviceString, value: name, icon: deviceIcon };
  }

  return " [".concat(i + 1, "]> ").concat(deviceString, "\n");
};

var resetAdb = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c, ranBefore) {return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:_context3.prev = 0;if (

            ranBefore) {_context3.next = 4;break;}_context3.next = 4;return (0, _exec.execCLI)(c, _constants.CLI_ANDROID_ADB, 'kill-server');case 4:_context3.next = 9;break;case 6:_context3.prev = 6;_context3.t0 = _context3["catch"](0);

            (0, _logger.logWarning)(_context3.t0);case 9:_context3.prev = 9;_context3.next = 12;return (


              (0, _exec.execCLI)(c, _constants.CLI_ANDROID_ADB, 'start-server'));case 12:_context3.next = 20;break;case 14:_context3.prev = 14;_context3.t1 = _context3["catch"](9);if (!

            ranBefore) {_context3.next = 18;break;}return _context3.abrupt("return",
            Promise.reject(_context3.t1));case 18:

            (0, _logger.logWarning)("Got error:\n".concat(_context3.t1, "\nWill attemnt again in 5 seconds"));
            setTimeout(resetAdb, 5000, c, true);case 20:case "end":return _context3.stop();}}}, _callee3, null, [[0, 6], [9, 14]]);}));return function resetAdb(_x4, _x5) {return _ref3.apply(this, arguments);};}();exports.resetAdb = resetAdb;



var getAndroidTargets = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(
  c,
  skipDevices,
  skipAvds) {var deviceOnly,devicesResult,avdResult,_args4 = arguments;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            deviceOnly = _args4.length > 3 && _args4[3] !== undefined ? _args4[3] : false;

            (0, _logger.logTask)(
            'getAndroidTargets', "skipDevices:".concat(
            !!skipDevices, " skipAvds:").concat(!!skipAvds, " deviceOnly:").concat(!!deviceOnly));_context4.prev = 2;if (






            skipDevices) {_context4.next = 7;break;}_context4.next = 6;return (
              (0, _exec.execCLI)(c, _constants.CLI_ANDROID_ADB, 'devices -l'));case 6:devicesResult = _context4.sent;case 7:if (

            skipAvds) {_context4.next = 11;break;}_context4.next = 10;return (
              (0, _exec.execCLI)(c, _constants.CLI_ANDROID_EMULATOR, '-list-avds'));case 10:avdResult = _context4.sent;case 11:return _context4.abrupt("return",

            _parseDevicesResult(c, devicesResult, avdResult, deviceOnly));case 14:_context4.prev = 14;_context4.t0 = _context4["catch"](2);return _context4.abrupt("return",

            Promise.reject(_context4.t0));case 17:case "end":return _context4.stop();}}}, _callee4, null, [[2, 14]]);}));return function getAndroidTargets(_x6, _x7, _x8) {return _ref4.apply(this, arguments);};}();exports.getAndroidTargets = getAndroidTargets;



var calculateDeviceDiagonal = function calculateDeviceDiagonal(width, height, density) {
  // Calculate the diagonal in inches
  var widthInches = width / density;
  var heightInches = height / density;
  return Math.sqrt(widthInches * widthInches + heightInches * heightInches);
};

var getRunningDeviceProp = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c, udid, prop) {var rawProps, reg, lines;return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:if (!

            currentDeviceProps[udid]) {_context5.next = 4;break;}if (
            prop) {_context5.next = 3;break;}return _context5.abrupt("return", currentDeviceProps[udid]);case 3:return _context5.abrupt("return",
            currentDeviceProps[udid][prop]);case 4:_context5.next = 6;return (

              (0, _exec.execCLI)(
              c,
              _constants.CLI_ANDROID_ADB, "-s ".concat(
              udid, " shell getprop")));case 6:rawProps = _context5.sent;

            reg = /\[.+\]: \[.*\n?[^[]*\]/gm;
            lines = rawProps.match(reg);

            lines.forEach(function (line) {
              var words = line.split(']: [');
              var key = words[0].slice(1);
              var value = words[1].slice(0, words[1].length - 1);

              if (!currentDeviceProps[udid]) currentDeviceProps[udid] = {};
              currentDeviceProps[udid][key] = value;
            });return _context5.abrupt("return",

            getRunningDeviceProp(c, udid, prop));case 11:case "end":return _context5.stop();}}}, _callee5);}));return function getRunningDeviceProp(_x9, _x10, _x11) {return _ref5.apply(this, arguments);};}();


var decideIfTVRunning = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(c, device) {var udid, model, product, mod, name, flavor, clientIdBase, description, hdmi, modelGroup, configuration, cecEnabled, isTV;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
            udid = device.udid, model = device.model, product = device.product;_context6.next = 3;return (
              getRunningDeviceProp(c, udid, 'ro.product.model'));case 3:mod = _context6.sent;_context6.next = 6;return (
              getRunningDeviceProp(c, udid, 'ro.product.name'));case 6:name = _context6.sent;_context6.next = 9;return (
              getRunningDeviceProp(c, udid, 'ro.build.flavor'));case 9:flavor = _context6.sent;_context6.next = 12;return (
              getRunningDeviceProp(
              c,
              udid,
              'ro.com.google.clientidbase'));case 12:clientIdBase = _context6.sent;_context6.next = 15;return (

              getRunningDeviceProp(
              c,
              udid,
              'ro.build.description'));case 15:description = _context6.sent;_context6.next = 18;return (

              getRunningDeviceProp(c, udid, 'init.svc.hdmi'));case 18:hdmi = _context6.sent;_context6.next = 21;return (
              getRunningDeviceProp(
              c,
              udid,
              'ro.nrdp.modelgroup'));case 21:modelGroup = _context6.sent;_context6.next = 24;return (

              getRunningDeviceProp(
              c,
              udid,
              'ro.build.configuration'));case 24:configuration = _context6.sent;_context6.next = 27;return (

              getRunningDeviceProp(
              c,
              udid,
              'persist.sys.cec.enabled'));case 27:cecEnabled = _context6.sent;


            isTV = false;
            [mod, name, flavor, clientIdBase, description, model, product].forEach(
            function (string) {
              if (string && string.toLowerCase().includes('tv')) isTV = true;
            });


            if (model.includes('SHIELD')) isTV = true;
            if (hdmi) isTV = true;
            if (modelGroup && modelGroup.toLowerCase().includes('firetv')) isTV = true;
            if (configuration === 'tv') isTV = true;
            if (cecEnabled) isTV = true;return _context6.abrupt("return",

            isTV);case 36:case "end":return _context6.stop();}}}, _callee6);}));return function decideIfTVRunning(_x12, _x13) {return _ref6.apply(this, arguments);};}();


var decideIfWearRunning = /*#__PURE__*/function () {var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(c, device) {var udid, model, product, fingerprint, name, mod, flavor, description, isWear;return regeneratorRuntime.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
            udid = device.udid, model = device.model, product = device.product;_context7.next = 3;return (
              getRunningDeviceProp(
              c,
              udid,
              'ro.vendor.build.fingerprint'));case 3:fingerprint = _context7.sent;_context7.next = 6;return (

              getRunningDeviceProp(c, udid, 'ro.product.vendor.name'));case 6:name = _context7.sent;_context7.next = 9;return (
              getRunningDeviceProp(c, udid, 'ro.product.vendor.model'));case 9:mod = _context7.sent;_context7.next = 12;return (
              getRunningDeviceProp(c, udid, 'ro.build.flavor'));case 12:flavor = _context7.sent;_context7.next = 15;return (
              getRunningDeviceProp(
              c,
              udid,
              'ro.build.description'));case 15:description = _context7.sent;


            isWear = false;
            [fingerprint, name, mod, flavor, description, model, product].forEach(
            function (string) {
              var cmp = string ? string.toLowerCase() : '';
              if (cmp.includes('wear') || cmp.includes('rubyfish') || cmp.includes('watch')) isWear = true;
            });return _context7.abrupt("return",

            isWear);case 19:case "end":return _context7.stop();}}}, _callee7);}));return function decideIfWearRunning(_x14, _x15) {return _ref7.apply(this, arguments);};}();


var getDeviceType = /*#__PURE__*/function () {var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(device, c) {var screenSizeResult, screenDensityResult, arch, screenProps, _screenSizeResult$spl, _screenSizeResult$spl2, width, height, density, _screenProps, _width, _height, _density, diagonalInches, _density2, _width2, _height2, _arch, sysdir, tagId, tagDisplay, deviceName, avdId, name, skin, image, _diagonalInches;return regeneratorRuntime.wrap(function _callee8$(_context8) {while (1) {switch (_context8.prev = _context8.next) {case 0:
            (0, _logger.logDebug)('getDeviceType - in', { device: device });if (!(

            device.udid !== 'unknown')) {_context8.next = 30;break;}_context8.next = 4;return (
              (0, _exec.execCLI)(
              c,
              _constants.CLI_ANDROID_ADB, "-s ".concat(
              device.udid, " shell wm size")));case 4:screenSizeResult = _context8.sent;_context8.next = 7;return (

              (0, _exec.execCLI)(
              c,
              _constants.CLI_ANDROID_ADB, "-s ".concat(
              device.udid, " shell wm density")));case 7:screenDensityResult = _context8.sent;_context8.next = 10;return (

              getRunningDeviceProp(
              c,
              device.udid,
              'ro.product.cpu.abi'));case 10:arch = _context8.sent;



            if (screenSizeResult) {_screenSizeResult$spl =
              screenSizeResult.
              split('Physical size: ')[1].
              split('x'), _screenSizeResult$spl2 = _slicedToArray(_screenSizeResult$spl, 2), width = _screenSizeResult$spl2[0], height = _screenSizeResult$spl2[1];
              screenProps = {
                width: parseInt(width, 10),
                height: parseInt(height, 10) };

            }

            if (screenDensityResult) {
              density = screenDensityResult.split('Physical density: ')[1];
              screenProps = _objectSpread(_objectSpread({}, screenProps), {}, { density: parseInt(density, 10) });
            }_context8.next = 15;return (

              decideIfTVRunning(c, device));case 15:device.isTV = _context8.sent;if (!(

            screenSizeResult && screenDensityResult)) {_context8.next = 24;break;}_screenProps =
            screenProps, _width = _screenProps.width, _height = _screenProps.height, _density = _screenProps.density;

            diagonalInches = calculateDeviceDiagonal(
            _width,
            _height,
            _density);

            screenProps = _objectSpread(_objectSpread({}, screenProps), {}, { diagonalInches: diagonalInches });
            device.isTablet = !device.isTV &&
            diagonalInches > _constants.IS_TABLET_ABOVE_INCH &&
            diagonalInches <= 15;_context8.next = 23;return (
              decideIfWearRunning(c, device));case 23:device.isWear = _context8.sent;case 24:


            device.isPhone = !device.isTablet && !device.isWear && !device.isTV;
            device.isMobile = !device.isWear && !device.isTV;
            device.screenProps = screenProps;
            device.arch = arch;
            (0, _logger.logDebug)('getDeviceType - out', { device: device });return _context8.abrupt("return",
            device);case 30:if (!


            device.avdConfig) {_context8.next = 54;break;}
            _density2 = parseInt(device.avdConfig['hw.lcd.density'], 10);
            _width2 = parseInt(device.avdConfig['hw.lcd.width'], 10);
            _height2 = parseInt(device.avdConfig['hw.lcd.height'], 10);
            _arch = device.avdConfig['abi.type'];

            // Better detect wear
            sysdir = device.avdConfig['image.sysdir.1'];
            tagId = device.avdConfig['tag.id'];
            tagDisplay = device.avdConfig['tag.display'];
            deviceName = device.avdConfig['hw.device.name'];

            device.isWear = false;
            [sysdir, tagId, tagDisplay, deviceName].forEach(function (string) {
              if (string && string.includes('wear')) device.isWear = true;
            });

            avdId = device.avdConfig.AvdId;
            name = device.avdConfig['hw.device.name'];
            skin = device.avdConfig['skin.name'];
            image = device.avdConfig['image.sysdir.1'];

            device.isTV = false;
            [avdId, name, skin, image].forEach(function (string) {
              if (string && string.toLowerCase().includes('tv')) {
                device.isTV = true;
              }
            });

            _diagonalInches = calculateDeviceDiagonal(_width2, _height2, _density2);
            device.isTablet = !device.isTV && _diagonalInches > _constants.IS_TABLET_ABOVE_INCH;
            device.isPhone = !device.isTablet && !device.isWear && !device.isTV;
            device.isMobile = !device.isWear && !device.isTV;
            device.arch = _arch;
            (0, _logger.logDebug)('getDeviceType - out', { device: device });return _context8.abrupt("return",
            device);case 54:return _context8.abrupt("return",

            device);case 55:case "end":return _context8.stop();}}}, _callee8);}));return function getDeviceType(_x16, _x17) {return _ref8.apply(this, arguments);};}();


var getAvdDetails = function getAvdDetails(c, deviceName) {
  var _process$env = process.env,ANDROID_SDK_HOME = _process$env.ANDROID_SDK_HOME,ANDROID_AVD_HOME = _process$env.ANDROID_AVD_HOME;

  // .avd dir might be in other place than homedir. (https://developer.android.com/studio/command-line/variables)
  var avdConfigPaths = ["".concat(
  ANDROID_AVD_HOME), "".concat(
  ANDROID_SDK_HOME, "/.android/avd"), "".concat(
  _constants.USER_HOME_DIR, "/.android/avd")];


  var results = {};

  avdConfigPaths.forEach(function (cPath) {
    if ((0, _fileutils.fsExistsSync)(cPath)) {
      var filesPath = (0, _fileutils.fsReaddirSync)(cPath);

      filesPath.forEach(function (fName) {
        var fPath = _path["default"].join(cPath, fName);
        var dirent = (0, _fileutils.fsLstatSync)(fPath);
        if (!dirent.isDirectory() && fName === "".concat(deviceName, ".ini")) {
          var avdData = (0, _fileutils.fsReadFileSync)(fPath).toString();
          var lines = avdData.trim().split(/\r?\n/);
          lines.forEach(function (line) {
            var _line$split = line.split('='),_line$split2 = _slicedToArray(_line$split, 2),key = _line$split2[0],value = _line$split2[1];
            if (key === 'path') {
              var initData = (0, _fileutils.fsReadFileSync)("".concat(value, "/config.ini")).
              toString();
              var initLines = initData.trim().split(/\r?\n/);
              var avdConfig = {};
              initLines.forEach(function (initLine) {
                var _initLine$split = initLine.split('='),_initLine$split2 = _slicedToArray(_initLine$split, 2),iniKey = _initLine$split2[0],iniValue = _initLine$split2[1];
                // also remove the white space
                avdConfig[iniKey.trim()] = iniValue.trim();
              });
              results.avdConfig = avdConfig;
            }
          });
        }
      });
    }
  });
  return results;
};

var getEmulatorName = /*#__PURE__*/function () {var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(c, words) {var _emulatorNameStr$trim;var emulator, port, emulatorReply, emulatorReplyArray, emulatorNameStr, emulatorName;return regeneratorRuntime.wrap(function _callee9$(_context9) {while (1) {switch (_context9.prev = _context9.next) {case 0:
            emulator = words[0];
            port = emulator.split('-')[1];_context9.next = 4;return (

              (0, _exec.executeTelnet)(c, port, 'avd name'));case 4:emulatorReply = _context9.sent;
            emulatorReplyArray = emulatorReply.split('OK');
            emulatorNameStr = emulatorReplyArray[
            emulatorReplyArray.length - 2];

            emulatorName = (emulatorNameStr === null || emulatorNameStr === void 0 ? void 0 : (_emulatorNameStr$trim = emulatorNameStr.trim) === null || _emulatorNameStr$trim === void 0 ? void 0 : _emulatorNameStr$trim.call(emulatorNameStr)) || '(err: could not parse emulator name)';return _context9.abrupt("return",
            emulatorName);case 9:case "end":return _context9.stop();}}}, _callee9);}));return function getEmulatorName(_x18, _x19) {return _ref9.apply(this, arguments);};}();


var connectToWifiDevice = /*#__PURE__*/function () {var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(c, target) {var connect_str, deviceResponse;return regeneratorRuntime.wrap(function _callee10$(_context10) {while (1) {switch (_context10.prev = _context10.next) {case 0:
            connect_str = "connect ".concat(target);

            if (!target.includes(':')) {
              connect_str = "connect ".concat(target, ":5555");
            }_context10.next = 4;return (

              (0, _exec.execCLI)(
              c,
              _constants.CLI_ANDROID_ADB,
              connect_str));case 4:deviceResponse = _context10.sent;if (!

            deviceResponse.includes('connected')) {_context10.next = 7;break;}return _context10.abrupt("return", true);case 7:
            (0, _logger.logError)("Failed to ".concat(connect_str), false, true);return _context10.abrupt("return",
            false);case 9:case "end":return _context10.stop();}}}, _callee10);}));return function connectToWifiDevice(_x20, _x21) {return _ref10.apply(this, arguments);};}();exports.connectToWifiDevice = connectToWifiDevice;


var _parseDevicesResult = /*#__PURE__*/function () {var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(
  c,
  devicesString,
  avdsString,
  deviceOnly) {var devices, skipTargetCheck, lines, avdLines;return regeneratorRuntime.wrap(function _callee13$(_context13) {while (1) {switch (_context13.prev = _context13.next) {case 0:

            (0, _logger.logDebug)("_parseDevicesResult:".concat(
            devicesString, ":").concat(avdsString, ":").concat(deviceOnly));

            devices = [];
            skipTargetCheck = c.program.skipTargetCheck;if (!

            devicesString) {_context13.next = 9;break;}
            lines = devicesString.trim().split(/\r?\n/);
            (0, _logger.logDebug)('_parseDevicesResult 2', { lines: lines });if (!(
            lines.length !== 0)) {_context13.next = 9;break;}_context13.next = 9;return (
              Promise.all(
              lines.map( /*#__PURE__*/function () {var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(line) {var words, isDevice, name, model, product;return regeneratorRuntime.wrap(function _callee11$(_context11) {while (1) {switch (_context11.prev = _context11.next) {case 0:
                          words = line.split(/[ ,\t]+/).filter(function (w) {return w !== '';});if (!(
                          words.length === 0)) {_context11.next = 3;break;}return _context11.abrupt("return");case 3:
                          (0, _logger.logDebug)('_parseDevicesResult 3', { words: words });if (!(

                          words[1] === 'device')) {_context11.next = 20;break;}
                          isDevice = !words[0].includes('emulator');
                          name = _getDeviceProp(words, 'model:');
                          model = name;
                          product = _getDeviceProp(words, 'product:');
                          (0, _logger.logDebug)('_parseDevicesResult 4', { name: name });if (
                          isDevice) {_context11.next = 17;break;}_context11.next = 13;return (
                            waitForEmulatorToBeReady(c, words[0]));case 13:_context11.next = 15;return (
                            getEmulatorName(c, words));case 15:name = _context11.sent;
                          (0, _logger.logDebug)('_parseDevicesResult 5', { name: name });case 17:

                          (0, _logger.logDebug)('_parseDevicesResult 6', {
                            deviceOnly: deviceOnly,
                            isDevice: isDevice });

                          if (deviceOnly && isDevice || !deviceOnly) {
                            devices.push({
                              udid: words[0],
                              isDevice: isDevice,
                              isActive: true,
                              name: name,
                              model: model,
                              product: product });

                          }return _context11.abrupt("return",
                          true);case 20:case "end":return _context11.stop();}}}, _callee11);}));return function (_x26) {return _ref12.apply(this, arguments);};}())));case 9:if (!






            avdsString) {_context13.next = 14;break;}
            avdLines = avdsString.trim().split(/\r?\n/);
            (0, _logger.logDebug)('_parseDevicesResult 7', { avdLines: avdLines });_context13.next = 14;return (

              Promise.all(
              avdLines.map( /*#__PURE__*/function () {var _ref13 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(line) {var avdDetails, findProcess;return regeneratorRuntime.wrap(function _callee12$(_context12) {while (1) {switch (_context12.prev = _context12.next) {case 0:


                          try {
                            avdDetails = getAvdDetails(c, line);
                          } catch (e) {
                            (0, _logger.logError)(e);
                          }

                          try {
                            (0, _logger.logDebug)('_parseDevicesResult 8', { avdDetails: avdDetails });

                            // Yes, 2 greps. Hacky but it excludes the grep process corectly and quickly :)
                            // if this runs without throwing it means that the simulator is running so it needs to be excluded
                            // Yes, 2 greps. Hacky but it excludes the grep process corectly and quickly :)
                            // if this runs without throwing it means that the simulator is running so it needs to be excluded
                            findProcess = _utils.isSystemWin ? "tasklist | find \"avd ".concat(line, "\"") : "ps x | grep \"avd ".concat(line, "\" | grep -v grep");
                            _child_process["default"].execSync(findProcess);
                            (0, _logger.logDebug)(
                            '_parseDevicesResult 9 - excluding running emulator');

                          } catch (e) {
                            if (avdDetails) {
                              devices.push(_objectSpread({
                                udid: 'unknown',
                                isDevice: false,
                                isActive: false,
                                name: line },
                              avdDetails));

                            }
                          }case 2:case "end":return _context12.stop();}}}, _callee12);}));return function (_x27) {return _ref13.apply(this, arguments);};}())));case 14:




            (0, _logger.logDebug)('_parseDevicesResult 10', { devices: devices });return _context13.abrupt("return",

            Promise.all(devices.map(function (device) {return getDeviceType(device, c);})).then(
            function (devicesArray) {return devicesArray.filter(function (device) {
                // filter devices based on selected platform
                var platform = c.platform;
                if (skipTargetCheck) return true; // return everything if skipTargetCheck is used
                // return everything if skipTargetCheck is used
                if (device.isNotEligibleAndroid) return false;var matches = platform === _constants.ANDROID && device.isTablet ||
                platform === _constants.ANDROID_WEAR && device.isWear ||
                platform === _constants.ANDROID_TV && device.isTV ||
                platform === _constants.FIRE_TV && device.isTV ||
                platform === _constants.ANDROID && device.isMobile;
                (0, _logger.logDebug)('getDeviceType - filter', {
                  device: device,
                  matches: matches,
                  platform: platform });

                return matches;
              });}));case 16:case "end":return _context13.stop();}}}, _callee13);}));return function _parseDevicesResult(_x22, _x23, _x24, _x25) {return _ref11.apply(this, arguments);};}();



var _getDeviceProp = function _getDeviceProp(arr, prop) {
  for (var i = 0; i < arr.length; i++) {
    var v = arr[i];
    if (v && v.includes(prop)) return v.replace(prop, '');
  }
  return '';
};

var askForNewEmulator = /*#__PURE__*/function () {var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(c, platform) {var emuName, _yield$inquirer$promp, confirm;return regeneratorRuntime.wrap(function _callee14$(_context14) {while (1) {switch (_context14.prev = _context14.next) {case 0:
            (0, _logger.logTask)('askForNewEmulator');
            emuName = c.files.workspace.config.defaultTargets[platform];_context14.next = 4;return (

              _inquirer["default"].prompt({
                name: 'confirm',
                type: 'confirm',
                message: "Do you want ReNative to create new Emulator (".concat((0, _logger.chalk)().white(
                emuName), ") for you?") }));case 4:_yield$inquirer$promp = _context14.sent;confirm = _yield$inquirer$promp.confirm;if (!



            confirm) {_context14.next = 14;break;}_context14.t0 =
            platform;_context14.next = _context14.t0 ===
            'android' ? 10 : _context14.t0 ===



            'androidtv' ? 11 : _context14.t0 ===



            'androidwear' ? 12 : 13;break;case 10:return _context14.abrupt("return", _createEmulator(c, '28', 'google_apis', emuName).then(function () {return launchAndroidSimulator(c, emuName, true);}));case 11:return _context14.abrupt("return", _createEmulator(c, '28', 'android-tv', emuName).then(function () {return launchAndroidSimulator(c, emuName, true);}));case 12:return _context14.abrupt("return",
            _createEmulator(c, '28', 'android-wear', emuName).then(
            function () {return launchAndroidSimulator(c, emuName, true);}));case 13:return _context14.abrupt("return",


            Promise.reject(
            'Cannot find any active or created emulators'));case 14:return _context14.abrupt("return",



            Promise.reject('Action canceled!'));case 15:case "end":return _context14.stop();}}}, _callee14);}));return function askForNewEmulator(_x28, _x29) {return _ref14.apply(this, arguments);};}();exports.askForNewEmulator = askForNewEmulator;


var _createEmulator = function _createEmulator(c, apiVersion, emuPlatform, emuName) {
  (0, _logger.logTask)('_createEmulator');

  return (0, _exec.execCLI)(
  c,
  _constants.CLI_ANDROID_SDKMANAGER, "\"system-images;android-".concat(
  apiVersion, ";").concat(emuPlatform, ";x86\"")).

  then(function () {return (0, _exec.execCLI)(
    c,
    _constants.CLI_ANDROID_AVDMANAGER, "create avd -n ".concat(
    emuName, " -k \"system-images;android-").concat(apiVersion, ";").concat(emuPlatform, ";x86\""),
    {
      interactive: true });})["catch"](


  function (e) {return (0, _logger.logError)(e, true);});
};

var waitForEmulatorToBeReady = function waitForEmulatorToBeReady(c, emulator) {return (0, _common.waitForEmulator)(
  c,
  _constants.CLI_ANDROID_ADB, "-s ".concat(
  emulator, " shell getprop init.svc.bootanim"),
  function (res) {return res.includes('stopped');});};


var checkForActiveEmulator = function checkForActiveEmulator(c) {return new Promise(function (resolve, reject) {
    (0, _logger.logTask)('checkForActiveEmulator');
    var platform = c.platform;
    var attempts = 1;
    var maxAttempts = _utils.isSystemWin ? 20 : 10;
    var running = false;
    var poll = setInterval(function () {
      // Prevent the interval from running until enough promises return to make it stop or we get a result
      if (!running) {
        running = true;
        getAndroidTargets(c, false, true, false).
        then( /*#__PURE__*/function () {var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15(v) {return regeneratorRuntime.wrap(function _callee15$(_context15) {while (1) {switch (_context15.prev = _context15.next) {case 0:
                    (0, _logger.logDebug)('Available devices after filtering', v);if (!(
                    v.length > 0)) {_context15.next = 7;break;}
                    (0, _logger.logSuccess)("Found active emulator! ".concat(
                    (0, _logger.chalk)().white(
                    v[0].udid), ". Will use it"));


                    clearInterval(poll);
                    resolve(v[0]);_context15.next = 14;break;case 7:

                    (0, _logger.logRaw)("looking for active emulators: attempt ".concat(
                    attempts, "/").concat(maxAttempts));

                    attempts++;if (!(

                    [_constants.ANDROID_TV, _constants.FIRE_TV, _constants.ANDROID_WEAR].includes(platform) &&
                    attempts === 2)) {_context15.next = 12;break;}_context15.next = 12;return (

                      resetAdb(c));case 12:

                    if (attempts > maxAttempts) {
                      clearInterval(poll);
                      reject('Could not find any active emulators');
                      // TODO: Asking for new emulator is worng as it diverts
                      // user from underlying failure of not being able to connect
                      // return _askForNewEmulator(c, platform);
                    }
                    running = false;case 14:case "end":return _context15.stop();}}}, _callee15);}));return function (_x30) {return _ref15.apply(this, arguments);};}())["catch"](


        function (e) {
          clearInterval(poll);
          (0, _logger.logError)(e);
        });
      }
    }, CHECK_INTEVAL);
  });};exports.checkForActiveEmulator = checkForActiveEmulator;
//# sourceMappingURL=android.js.map