"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.runWebosSimOrDevice = exports.listWebOSTargets = exports.launchWebOSimulator = void 0;var _path = _interopRequireDefault(require("path"));
var _inquirer = _interopRequireDefault(require("inquirer"));
var _fileutils = require("../../systemManager/fileutils");
var _exec = require("../../systemManager/exec");
var _common = require("../../common");

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







var _constants = require("../../constants");







var _utils = require("../../systemManager/utils");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": 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 launchWebOSimulator = function launchWebOSimulator(c) {var _c$buildConfig, _c$buildConfig$sdks, _c$buildConfig2, _c$buildConfig2$sdks;
  (0, _logger.logTask)('launchWebOSimulator');

  var availableEmulatorVersions = (0, _fileutils.getDirectories)(_path["default"].join(
  (0, _fileutils.getRealPath)(c, (_c$buildConfig = c.buildConfig) === null || _c$buildConfig === void 0 ? void 0 : (_c$buildConfig$sdks = _c$buildConfig.sdks) === null || _c$buildConfig$sdks === void 0 ? void 0 : _c$buildConfig$sdks.WEBOS_SDK),
  'Emulator'));


  var ePath = _path["default"].join(
  (0, _fileutils.getRealPath)(c, (_c$buildConfig2 = c.buildConfig) === null || _c$buildConfig2 === void 0 ? void 0 : (_c$buildConfig2$sdks = _c$buildConfig2.sdks) === null || _c$buildConfig2$sdks === void 0 ? void 0 : _c$buildConfig2$sdks.WEBOS_SDK), "Emulator/".concat(
  (availableEmulatorVersions === null || availableEmulatorVersions === void 0 ? void 0 : availableEmulatorVersions[0]) || 'v4.0.0', "/LG_webOS_TV_Emulator").concat(
  _utils.isSystemWin ? '.exe' : '_RCU.app'));



  if (!(0, _fileutils.fsExistsSync)(ePath)) {
    return Promise.reject("Can't find emulator at path: ".concat(ePath));
  }
  if (_utils.isSystemWin) {return (0, _exec.executeAsync)(c, ePath, { detached: true, stdio: 'ignore' });}
  return (0, _exec.executeAsync)(c, "".concat(_exec.openCommand, " ").concat(ePath), { detached: true });
};

// const startHostedServerIfRequired = (c) => {
//     if (Config.isWebHostEnabled) {
//         return rnvStart(c);
//     }
// };
exports.launchWebOSimulator = launchWebOSimulator;
var parseDevices = function parseDevices(c, devicesResponse) {
  var linesArray = devicesResponse.
  split('\n').
  slice(2).
  map(function (line) {return line.trim();}).
  filter(function (line) {return line !== '';});
  return Promise.all(
  linesArray.map( /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(line) {var _line$split$map$filte, _line$split$map$filte2, name, device, connection, profile, deviceInfo;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_line$split$map$filte =
              line.
              split(' ').
              map(function (word) {return word.trim();}).
              filter(function (word) {return word !== '';}), _line$split$map$filte2 = _slicedToArray(_line$split$map$filte, 4), name = _line$split$map$filte2[0], device = _line$split$map$filte2[1], connection = _line$split$map$filte2[2], profile = _line$split$map$filte2[3];
              deviceInfo = '';_context.prev = 2;_context.next = 5;return (

                (0, _exec.execCLI)(
                c,
                _constants.CLI_WEBOS_ARES_DEVICE_INFO, "-d ".concat(
                name),
                { silent: true, timeout: 10000 }));case 5:deviceInfo = _context.sent;_context.next = 11;break;case 8:_context.prev = 8;_context.t0 = _context["catch"](2);


              deviceInfo = _context.t0;case 11:return _context.abrupt("return",


              {
                name: name,
                device: device,
                connection: connection,
                profile: profile,
                isDevice: !(0, _utils.isUrlLocalhost)(device),
                active: !deviceInfo.includes('ERR!') });case 12:case "end":return _context.stop();}}}, _callee, null, [[2, 8]]);}));return function (_x) {return _ref.apply(this, arguments);};}()));



};

var installAndLaunchApp = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, target, appPath, tId) {var toReturn;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:_context2.prev = 0;_context2.next = 3;return (

              (0, _exec.execCLI)(
              c,
              _constants.CLI_WEBOS_ARES_INSTALL, "--device ".concat(
              target, " ").concat(appPath)));case 3:_context2.next = 9;break;case 5:_context2.prev = 5;_context2.t0 = _context2["catch"](0);_context2.next = 9;return (




              (0, _exec.execCLI)(
              c,
              _constants.CLI_WEBOS_ARES_INSTALL, "--device ".concat(
              target, " ").concat(appPath)));case 9:


            // const { hosted } = c.program;
            // const { platform } = c;
            // const isHosted = hosted || !getConfigProp(c, platform, 'bundleAssets');
            toReturn = true;
            // if (isHosted) {
            //     toReturn = startHostedServerIfRequired(c);
            //     await waitForHost(c);
            // }
            _context2.next = 12;return (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_LAUNCH, "--device ".concat(target, " ").concat(tId));case 12:return _context2.abrupt("return",
            toReturn);case 13:case "end":return _context2.stop();}}}, _callee2, null, [[0, 5]]);}));return function installAndLaunchApp(_x2, _x3, _x4, _x5) {return _ref2.apply(this, arguments);};}();


var buildDeviceChoices = function buildDeviceChoices(devices) {return devices.map(function (device) {return {
      key: device.name,
      name: "".concat(device.name, " - ").concat(device.device),
      value: device.name };});};


var listWebOSTargets = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c) {var devicesResponse, devices, deviceArray;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:_context3.next = 2;return (
              (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_DEVICE_INFO, '-D'));case 2:devicesResponse = _context3.sent;_context3.next = 5;return (
              parseDevices(c, devicesResponse));case 5:devices = _context3.sent;

            deviceArray = devices.map(
            function (device, i) {return " [".concat(i + 1, "]> ").concat((0, _logger.chalk)().bold(device.name), " | ").concat(device.device);});


            (0, _logger.logToSummary)("WebOS Targets:\n".concat(deviceArray.join('\n')));return _context3.abrupt("return",

            true);case 9:case "end":return _context3.stop();}}}, _callee3);}));return function listWebOSTargets(_x6) {return _ref3.apply(this, arguments);};}();exports.listWebOSTargets = listWebOSTargets;


var waitForEmulatorToBeReady = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var devicesResponse, devices, emulator;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:_context4.next = 2;return (
              (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_DEVICE_INFO, '-D'));case 2:devicesResponse = _context4.sent;_context4.next = 5;return (
              parseDevices(c, devicesResponse));case 5:devices = _context4.sent;
            emulator = devices.filter(function (d) {return !d.isDevice;})[0];if (
            emulator) {_context4.next = 9;break;}throw new Error('No WebOS emulator configured');case 9:return _context4.abrupt("return",

            (0, _common2.waitForEmulator)(
            c,
            _constants.CLI_WEBOS_ARES_DEVICE_INFO, "-d ".concat(
            emulator.name),
            function (res) {return res.includes('modelName');}));case 10:case "end":return _context4.stop();}}}, _callee4);}));return function waitForEmulatorToBeReady(_x7) {return _ref4.apply(this, arguments);};}();



var runWebosSimOrDevice = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c) {var device, tDir, tOut, tSim, configFilePath, cnfg, tId, appPath, devicesResponse, devices, activeDevices, actualDevices, response, newDeviceResponse, dev, actualDev, newDevice, tv, choices, _response;return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
            device = c.program.device;

            tDir = (0, _common.getPlatformProjectDir)(c);
            tOut = _path["default"].join((0, _common.getPlatformBuildDir)(c), 'output');
            tSim = c.program.target || 'emulator';
            configFilePath = _path["default"].join(tDir, 'appinfo.json');

            // logTask(`runWebOS:${target}:${isHosted}`, chalk().grey);
            cnfg = JSON.parse((0, _fileutils.fsReadFileSync)(configFilePath, 'utf-8'));
            tId = cnfg.id;
            appPath = _path["default"].join(tOut, "".concat(tId, "_").concat(cnfg.version, "_all.ipk"));


            // Start the fun
            // await buildWeb(c);
            _context5.next = 10;return (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_PACKAGE, "-o ".concat(tOut, " ").concat(tDir, " -n"));case 10:_context5.next = 12;return (


              (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_DEVICE_INFO, '-D'));case 12:devicesResponse = _context5.sent;_context5.next = 15;return (
              parseDevices(c, devicesResponse));case 15:devices = _context5.sent;
            activeDevices = devices.filter(function (d) {return d.active;});if (!

            device) {_context5.next = 47;break;}
            // Running on a device
            actualDevices = devices.filter(function (d) {return d.isDevice;});if (

            actualDevices.length) {_context5.next = 42;break;}_context5.next = 22;return (

              _inquirer["default"].prompt([
              {
                type: 'confirm',
                name: 'setupDevice',
                message:
                'You want to deploy on a device but have none configured. Do you want to configure one?',
                "default": false }]));case 22:response = _context5.sent;if (!



            response.setupDevice) {_context5.next = 40;break;}
            // Yes, I would like that
            (0, _logger.logInfo)(
            'Please follow the instructions from http://webostv.developer.lge.com/develop/app-test/#installDevModeApp on how to setup the TV and the connection with the PC. Then follow the onscreen prompts\n');_context5.next = 27;return (

              (0, _exec.execCLI)(c, _constants.CLI_WEBOS_ARES_SETUP_DEVICE, '', {
                interactive: true }));case 27:_context5.next = 29;return (


              (0, _exec.execCLI)(
              c,
              _constants.CLI_WEBOS_ARES_DEVICE_INFO,
              '-D'));case 29:newDeviceResponse = _context5.sent;_context5.next = 32;return (

              parseDevices(c, newDeviceResponse));case 32:dev = _context5.sent;
            actualDev = dev.filter(function (d) {return d.isDevice;});if (!(

            actualDev.length > 0)) {_context5.next = 40;break;}
            newDevice = actualDev[0];
            // Oh boy, oh boy, I did it! I have a TV connected!
            (0, _logger.logInfo)(
            "Please enter the `Passphrase` from the TV's Developer Mode app");_context5.next = 39;return (

              (0, _exec.execCLI)(
              c,
              _constants.CLI_WEBOS_ARES_NOVACOM, "--device ".concat(
              newDevice.name, " --getkey"),
              { stdio: 'inherit' }));case 39:return _context5.abrupt("return",

            installAndLaunchApp(c, newDevice.name, appPath, tId));case 40:_context5.next = 45;break;case 42:if (!(




            actualDevices.length === 1)) {_context5.next = 45;break;}
            tv = actualDevices[0];return _context5.abrupt("return",
            installAndLaunchApp(c, tv.name, appPath, tId));case 45:_context5.next = 67;break;case 47:if (

            c.program.target) {_context5.next = 66;break;}if (!(

            activeDevices.length === 1)) {_context5.next = 50;break;}return _context5.abrupt("return",

            installAndLaunchApp(c, devices[0].name, appPath, tId));case 50:if (!(

            activeDevices.length > 1)) {_context5.next = 59;break;}
            // More than one, choosing
            choices = buildDeviceChoices(devices);_context5.next = 54;return (
              _inquirer["default"].prompt([
              {
                name: 'chosenDevice',
                type: 'list',
                message: 'What device would you like to start the app?',
                choices: choices }]));case 54:_response = _context5.sent;if (!


            _response.chosenDevice) {_context5.next = 57;break;}return _context5.abrupt("return",
            installAndLaunchApp(
            c,
            _response.chosenDevice,
            appPath,
            tId));case 57:_context5.next = 64;break;case 59:_context5.next = 61;return (



              launchWebOSimulator(c));case 61:_context5.next = 63;return (
              waitForEmulatorToBeReady(c));case 63:return _context5.abrupt("return",
            installAndLaunchApp(c, tSim, appPath, tId));case 64:_context5.next = 67;break;case 66:return _context5.abrupt("return",



            installAndLaunchApp(c, c.program.target, appPath, tId));case 67:case "end":return _context5.stop();}}}, _callee5);}));return function runWebosSimOrDevice(_x8) {return _ref5.apply(this, arguments);};}();exports.runWebosSimOrDevice = runWebosSimOrDevice;
//# sourceMappingURL=webos.js.map