"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.runTizenSimOrDevice = exports.listTizenTargets = exports.launchTizenSimulator = exports.createDevelopTizenCertificate = exports.addDevelopTizenCertificate = exports.DEFAULT_SECURITY_PROFILE_NAME = exports.DEFAULT_CERTIFICATE_NAME = void 0;var _inquirer = _interopRequireDefault(require("inquirer"));
var _net = _interopRequireDefault(require("net"));
var _path = _interopRequireDefault(require("path"));
var _common = require("../../common");
var _constants = require("../../constants");


var _exec = require("../../systemManager/exec");
var _fileutils = require("../../systemManager/fileutils");
var _logger = require("../../systemManager/logger");


var _common2 = require("./common");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);});};}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;}


var xml2js = require('xml2js');

var parser = new xml2js.Parser();

var DEFAULT_CERTIFICATE_NAME = 'tizen_author';exports.DEFAULT_CERTIFICATE_NAME = DEFAULT_CERTIFICATE_NAME;


var formatXMLObject = function formatXMLObject(obj) {var _obj$modelConfig, _platArr$;
  var platArr = (_obj$modelConfig = obj['model-config']) === null || _obj$modelConfig === void 0 ? void 0 : _obj$modelConfig.platform;
  var platKeyArr = (platArr === null || platArr === void 0 ? void 0 : (_platArr$ = platArr[0]) === null || _platArr$ === void 0 ? void 0 : _platArr$.key) || (platArr === null || platArr === void 0 ? void 0 : platArr.key);
  if (platKeyArr) {
    return _objectSpread({},
    platKeyArr.reduce(function (acc, cur) {
      acc[cur.$.name] = cur._;
      return acc;
    }, {}));

  }
  (0, _logger.logWarning)('Invalid object received from shell cat /etc/config/model-config.xml');
  return {};
};

var DEFAULT_SECURITY_PROFILE_NAME = 'RNVanillaCert';exports.DEFAULT_SECURITY_PROFILE_NAME = DEFAULT_SECURITY_PROFILE_NAME;


var launchTizenSimulator = function launchTizenSimulator(c, name) {
  (0, _logger.logTask)("launchTizenSimulator:".concat(name));

  if (name) {
    return (0, _exec.execCLI)(c, _constants.CLI_TIZEN_EMULATOR, "launch --name ".concat(name), {
      detached: true });

  }
  return Promise.reject('No simulator -t target name specified!');
};exports.launchTizenSimulator = launchTizenSimulator;

var listTizenTargets = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c) {var targets, targetArr, targetStr;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.next = 2;return (
              (0, _exec.execCLI)(c, _constants.CLI_TIZEN_EMULATOR, 'list-vm', {
                detached: true }));case 2:targets = _context.sent;

            targetArr = targets.split('\n');
            targetStr = '';
            Object.keys(targetArr).forEach(function (i) {
              targetStr += "[".concat(i, "]> ").concat(targetArr[i], "\n");
            });
            (0, _logger.logToSummary)("Tizen Targets:\n".concat(targetStr));case 7:case "end":return _context.stop();}}}, _callee);}));return function listTizenTargets(_x) {return _ref.apply(this, arguments);};}();exports.listTizenTargets = listTizenTargets;


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

    var certDirPath = c.paths.workspace.dir;
    var certFilename = DEFAULT_CERTIFICATE_NAME;
    var certPassword = '1234';

    (0, _exec.execCLI)(
    c,
    _constants.CLI_TIZEN, "certificate -- ".concat(
    certDirPath, " -a rnv -f ").concat(certFilename, " -p ").concat(certPassword)
    // { privateParams: [certPassword] },
    ).
    then(function () {return addDevelopTizenCertificate(c, {
        profileName: DEFAULT_SECURITY_PROFILE_NAME,
        certPath: _path["default"].join(certDirPath, "".concat(certFilename, ".p12")),
        certPassword: certPassword });}).

    then(function () {return resolve();})["catch"](
    function (e) {
      (0, _logger.logError)(e);
      resolve();
    });
  });};exports.createDevelopTizenCertificate = createDevelopTizenCertificate;

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

    var _ref2 = secureProfileConfig || {},profileName = _ref2.profileName,certPath = _ref2.certPath,certPassword = _ref2.certPassword;
    (0, _exec.execCLI)(
    c,
    _constants.CLI_TIZEN, "security-profiles add -n ".concat(
    profileName, " -a ").concat(certPath, " -p ").concat(certPassword),
    { privateParams: [certPassword] }).

    then(function () {return resolve();})["catch"](
    function (e) {
      (0, _logger.logError)(e);
      resolve();
    });
  });};exports.addDevelopTizenCertificate = addDevelopTizenCertificate;

var _getDeviceID = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, target) {var device, connectResponse, devicesList, lines, devices, deviceID;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            device = c.program.device;if (!

            device) {_context2.next = 17;break;}_context2.prev = 2;_context2.next = 5;return (


              (0, _exec.execCLI)(
              c,
              _constants.CLI_SDB_TIZEN, "connect ".concat(
              target)));case 5:connectResponse = _context2.sent;_context2.next = 11;break;case 8:_context2.prev = 8;_context2.t0 = _context2["catch"](2);


            connectResponse = _context2.t0;case 11:if (!

            connectResponse.includes('EPERM')) {_context2.next = 13;break;}throw (
              new Error(
              "We can't connect to this device even though it is reachable. Please make sure you have enabled Developer Mode and you have added your IP in the Host PC IP section. For more information consult https://developer.samsung.com/tv/develop/getting-started/using-sdk/tv-device"));case 13:if (!


            connectResponse.includes('failed to connect to remote target')) {_context2.next = 15;break;}throw (
              new Error("Failed to connect to ".concat(
              target, ". Make sure the IP is correct and you are connected on the same network.")));case 15:if (!


            connectResponse.includes('error')) {_context2.next = 17;break;}throw new Error(connectResponse);case 17:_context2.next = 19;return (


              (0, _exec.execCLI)(c, _constants.CLI_SDB_TIZEN, 'devices'));case 19:devicesList = _context2.sent;if (!
            devicesList.includes(target)) {_context2.next = 26;break;}
            lines = devicesList.trim().split(/\r?\n/);
            devices = lines.filter(function (line) {return line.includes(target);});

            if (devices.length > 1) {
              // @todo handle more than one
            }

            deviceID = devices[0].split('device')[1].trim();return _context2.abrupt("return",
            deviceID);case 26:return _context2.abrupt("return",

            Promise.reject("No device matching ".concat(target, " could be found.")));case 27:case "end":return _context2.stop();}}}, _callee2, null, [[2, 8]]);}));return function _getDeviceID(_x2, _x3) {return _ref3.apply(this, arguments);};}();


var _getRunningDevices = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var platform, devicesList, lines, devices;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            platform = c.program.platform;_context4.next = 3;return (
              (0, _exec.execCLI)(c, _constants.CLI_SDB_TIZEN, 'devices'));case 3:devicesList = _context4.sent;
            lines = devicesList.
            trim().
            split(/\r?\n/).
            filter(function (line) {return !line.includes('List of devices');});
            devices = [];_context4.next = 8;return (

              Promise.all(
              lines.map( /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(line) {var words, name, deviceInfoXML, deviceInfo, deviceType, parseObj;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                          words = line.replace(/\t/g, '').split('    ');if (!(
                          words.length >= 3)) {_context3.next = 13;break;}
                          name = words[0].trim();_context3.next = 5;return (
                            (0, _exec.execCLI)(
                            c,
                            _constants.CLI_SDB_TIZEN, "-s ".concat(
                            name, " shell cat /etc/config/model-config.xml"),
                            { ignoreErrors: true }));case 5:deviceInfoXML = _context3.sent;if (!(





                          deviceInfoXML !== true && deviceInfoXML !== '')) {_context3.next = 12;break;}_context3.next = 9;return (


                            parser.parseStringPromise(deviceInfoXML));case 9:parseObj = _context3.sent;

                          deviceInfo = formatXMLObject(parseObj);
                          deviceType = deviceInfo['tizen.org/feature/profile'];case 12:


                          if (
                          platform === 'tizenmobile' && deviceType === 'mobile' ||
                          platform === 'tizenwatch' && deviceType === 'wearable' ||
                          platform === 'tizen' && !deviceType)
                          {
                            devices.push({
                              name: name,
                              type: words[1].trim(),
                              id: words[2].trim(),
                              deviceType: deviceType });

                          }case 13:case "end":return _context3.stop();}}}, _callee3);}));return function (_x5) {return _ref5.apply(this, arguments);};}())));case 8:return _context4.abrupt("return",




            devices);case 9:case "end":return _context4.stop();}}}, _callee4);}));return function _getRunningDevices(_x4) {return _ref4.apply(this, arguments);};}();


var _waitForEmulatorToBeReady = function _waitForEmulatorToBeReady(c, target) {return (0, _common2.waitForEmulator)(c, _constants.CLI_SDB_TIZEN, 'devices', function (res) {
    var lines = res.trim().split(/\r?\n/);
    var devices = lines.filter(
    function (line) {return line.includes(target) && line.includes('device');});

    return devices.length > 0;
  });};

var _composeDevicesString = function _composeDevicesString(devices) {return devices.map(function (device) {return {
      key: device.id,
      name: device.name,
      value: device.id };});};


// const startHostedServerIfRequired = (c) => {
//     if (Config.isWebHostEnabled) {
//         return rnvStart(c);
//     }
// };

var runTizenSimOrDevice = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(c, buildCoreWebpackProject) {var _platformConfig$certi;var hosted, _c$runtime, target, engine, platform, platformConfig, bundleAssets, isHosted, isLightningEngine, tDir, tBuild, tOut, tId, wgt, wgtClean, certProfile, deviceID, askForEmulator, continueLaunching, isTargetSpecified, devices, targetDevice, choices, _yield$inquirer$promp2, chosenEmulator;return regeneratorRuntime.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
            hosted = c.program.hosted;_c$runtime =
            c.runtime, target = _c$runtime.target, engine = _c$runtime.engine;
            platform = c.platform;

            platformConfig = c.buildConfig.platforms[platform];
            bundleAssets = (0, _common.getConfigProp)(c, platform, 'bundleAssets');
            isHosted = hosted !== null && hosted !== void 0 ? hosted : !bundleAssets;
            isLightningEngine = engine.config.id === 'engine-lightning';
            if (!bundleAssets && !hosted) {
              // console.log('RUN WEINRE');
            }if (

            platformConfig) {_context7.next = 10;break;}throw (
              new Error("runTizen: ".concat(
              (0, _logger.chalk)().grey(
              platform), " not defined in your ").concat(
              (0, _logger.chalk)().white(c.paths.appConfig.config))));case 10:if (


            platformConfig.appName) {_context7.next = 12;break;}throw (
              new Error("runTizen: ".concat(
              (0, _logger.chalk)().grey(
              platform), ".appName not defined in your ").concat(
              (0, _logger.chalk)().white(
              c.paths.appConfig.config))));case 12:




            tDir = (0, _common.getPlatformProjectDir)(c);
            tBuild = _path["default"].join(tDir, 'build');
            tOut = _path["default"].join(tDir, 'output');
            tId = platformConfig.id;
            wgt = "".concat(platformConfig.appName, ".wgt");
            // the tizen CLI cannot handle .wgt files with spaces correctly.
            wgtClean = "".concat(platformConfig.appName.replace(/[^a-z0-9]/gi, '_'), ".wgt");
            certProfile = (_platformConfig$certi = platformConfig.certificateProfile) !== null && _platformConfig$certi !== void 0 ? _platformConfig$certi : DEFAULT_SECURITY_PROFILE_NAME;



            askForEmulator = /*#__PURE__*/function () {var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {var _yield$inquirer$promp, startEmulator, defaultTarget;return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:_context5.next = 2;return (
                          _inquirer["default"].prompt([
                          {
                            name: 'startEmulator',
                            type: 'confirm',
                            message: "Could not find or connect to the specified target (".concat(
                            target, "). Would you like to start an emulator?") }]));case 2:_yield$inquirer$promp = _context5.sent;startEmulator = _yield$inquirer$promp.startEmulator;if (!




                        startEmulator) {_context5.next = 33;break;}
                        defaultTarget = c.files.workspace.config.defaultTargets[platform];_context5.prev = 6;_context5.next = 9;return (

                          launchTizenSimulator(c, defaultTarget));case 9:
                        deviceID = defaultTarget;_context5.next = 12;return (
                          _waitForEmulatorToBeReady(c, defaultTarget));case 12:return _context5.abrupt("return",
                        continueLaunching());case 15:_context5.prev = 15;_context5.t0 = _context5["catch"](6);

                        (0, _logger.logDebug)("askForEmulator:ERRROR: ".concat(_context5.t0));_context5.prev = 18;_context5.next = 21;return (

                          (0, _exec.execCLI)(
                          c,
                          _constants.CLI_TIZEN_EMULATOR, "create -n ".concat(
                          defaultTarget, " -p tv-samsung-5.0-x86")));case 21:_context5.next = 23;return (

                          launchTizenSimulator(c, defaultTarget));case 23:
                        deviceID = defaultTarget;_context5.next = 26;return (
                          _waitForEmulatorToBeReady(c, defaultTarget));case 26:return _context5.abrupt("return",
                        continueLaunching());case 29:_context5.prev = 29;_context5.t1 = _context5["catch"](18);

                        (0, _logger.logDebug)(_context5.t1);
                        (0, _logger.logError)("Could not find the specified target and could not create the emulator automatically.\nPlease create one and then edit the default target from ".concat(

                        c.paths.workspace.dir, "/").concat(_constants.RENATIVE_CONFIG_NAME));case 33:case "end":return _context5.stop();}}}, _callee5, null, [[6, 15], [18, 29]]);}));return function askForEmulator() {return _ref7.apply(this, arguments);};}();






            continueLaunching = /*#__PURE__*/function () {var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {var hasDevice, packageID, toReturn, _packageID;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
                        hasDevice = false;if (!(

                        !isLightningEngine && buildCoreWebpackProject)) {_context6.next = 10;break;}_context6.t0 =
                        !isHosted;if (!_context6.t0) {_context6.next = 6;break;}_context6.next = 6;return buildCoreWebpackProject(c);case 6:_context6.next = 8;return (
                          (0, _exec.execCLI)(c, _constants.CLI_TIZEN, "build-web -- ".concat(tDir, " -out ").concat(tBuild)));case 8:_context6.next = 10;return (
                          (0, _exec.execCLI)(
                          c,
                          _constants.CLI_TIZEN, "package -- ".concat(
                          tBuild, " -s ").concat(certProfile, " -t wgt -o ").concat(tOut)));case 10:_context6.prev = 10;




                        packageID = platform === 'tizenwatch' || platform === 'tizenmobile' ?
                        tId.split('.')[0] :
                        tId;_context6.next = 14;return (
                          (0, _exec.execCLI)(
                          c,
                          _constants.CLI_TIZEN, "uninstall -p ".concat(
                          packageID, " -t ").concat(deviceID),
                          { ignoreErrors: true }));case 14:

                        hasDevice = true;_context6.next = 25;break;case 17:_context6.prev = 17;_context6.t1 = _context6["catch"](10);if (!(

                        _context6.t1 && _context6.t1.includes && _context6.t1.includes('No device matching'))) {_context6.next = 25;break;}_context6.next = 22;return (
                          launchTizenSimulator(c, target));case 22:_context6.next = 24;return (
                          _waitForEmulatorToBeReady(c, target));case 24:hasDevice = _context6.sent;case 25:


                        try {
                          if (wgtClean !== wgt) {
                            (0, _logger.logInfo)("Your app name contains characters like spaces, changing output from \"".concat(
                            wgt, "\" to \"").concat(wgtClean, "\""));
                            (0, _fileutils.fsRenameSync)(_path["default"].join(tOut, wgt), _path["default"].join(tOut, wgtClean));
                          }
                        } catch (err) {
                          (0, _logger.logError)(err);
                        }_context6.prev = 26;_context6.next = 29;return (

                          (0, _exec.execCLI)(
                          c,
                          _constants.CLI_TIZEN, "install -- ".concat(
                          tOut, " -n ").concat(wgtClean, " -t ").concat(deviceID)));case 29:

                        hasDevice = true;_context6.next = 41;break;case 32:_context6.prev = 32;_context6.t2 = _context6["catch"](26);

                        (0, _logger.logError)(_context6.t2);
                        (0, _logger.logWarning)("There is no emulator or device connected! Let's try to launch it. \"".concat(
                        (0, _logger.chalk)().white.bold("rnv target launch -p ".concat(
                        platform, " -t ").concat(target)), "\""));_context6.next = 38;return (



                          launchTizenSimulator(c, target));case 38:_context6.next = 40;return (
                          _waitForEmulatorToBeReady(c, target));case 40:hasDevice = _context6.sent;case 41:


                        toReturn = true;

                        // if (isHosted) {
                        //     toReturn = startHostedServerIfRequired(c);
                        //     await waitForHost(c);
                        // }
                        if (!(

                        platform !== 'tizenwatch' &&
                        platform !== 'tizenmobile' &&
                        hasDevice)) {_context6.next = 47;break;}_context6.next = 45;return (

                          (0, _exec.execCLI)(c, _constants.CLI_TIZEN, "run -p ".concat(tId, " -t ").concat(deviceID)));case 45:_context6.next = 51;break;case 47:if (!(

                        (platform === 'tizenwatch' || platform === 'tizenmobile') &&
                        hasDevice)) {_context6.next = 51;break;}

                        _packageID = tId.split('.');_context6.next = 51;return (
                          (0, _exec.execCLI)(
                          c,
                          _constants.CLI_TIZEN, "run -p ".concat(
                          _packageID[0], " -t ").concat(deviceID)));case 51:return _context6.abrupt("return",


                        toReturn);case 52:case "end":return _context6.stop();}}}, _callee6, null, [[10, 17], [26, 32]]);}));return function continueLaunching() {return _ref8.apply(this, arguments);};}();


            // Check if target is present or it's the default one
            isTargetSpecified = c.program.target;

            // Check for running devices
            _context7.next = 24;return _getRunningDevices(c);case 24:devices = _context7.sent;if (!

            isTargetSpecified) {_context7.next = 50;break;}if (!

            _net["default"].isIP(target)) {_context7.next = 31;break;}_context7.next = 29;return (
              _getDeviceID(c, target));case 29:deviceID = _context7.sent;return _context7.abrupt("return",
            continueLaunching());case 31:if (!(


            devices.length > 0)) {_context7.next = 36;break;}
            targetDevice = devices.find(
            function (device) {return device.id === target || device.name === target;});if (!

            targetDevice) {_context7.next = 36;break;}
            deviceID = targetDevice.id;return _context7.abrupt("return",
            continueLaunching());case 36:_context7.prev = 36;_context7.next = 39;return (




              launchTizenSimulator(c, target));case 39:_context7.next = 41;return (
              _waitForEmulatorToBeReady(c, target));case 41:
            deviceID = target;return _context7.abrupt("return",
            continueLaunching());case 45:_context7.prev = 45;_context7.t0 = _context7["catch"](36);return _context7.abrupt("return",

            askForEmulator());case 48:_context7.next = 62;break;case 50:if (!(


            devices.length === 1)) {_context7.next = 53;break;}
            deviceID = devices[0].id;return _context7.abrupt("return",
            continueLaunching());case 53:if (!(

            devices.length > 1)) {_context7.next = 61;break;}
            choices = _composeDevicesString(devices);_context7.next = 57;return (
              _inquirer["default"].prompt([
              {
                name: 'chosenEmulator',
                type: 'list',
                message: 'On what emulator would you like to run the app?',
                choices: choices }]));case 57:_yield$inquirer$promp2 = _context7.sent;chosenEmulator = _yield$inquirer$promp2.chosenEmulator;


            deviceID = chosenEmulator;return _context7.abrupt("return",
            continueLaunching());case 61:return _context7.abrupt("return",

            askForEmulator());case 62:case "end":return _context7.stop();}}}, _callee7, null, [[36, 45]]);}));return function runTizenSimOrDevice(_x6, _x7) {return _ref6.apply(this, arguments);};}();exports.runTizenSimOrDevice = runTizenSimOrDevice;
//# sourceMappingURL=tizen.js.map