"use strict";

var _getIterator2 = require("babel-runtime/core-js/get-iterator");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _promise = require("babel-runtime/core-js/promise");

var _promise2 = _interopRequireDefault(_promise);

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require("babel-runtime/helpers/createClass");

var _createClass3 = _interopRequireDefault(_createClass2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var mlink = require("../index");
var WebsocketTerminal = mlink.Terminal.WebsocketTerminal;
var URL = require("url");
var WebSocket = require("ws");

var _require = require("../../util"),
    request = _require.request;

var config = require("../../config");

var _require2 = require("../../util"),
    logger = _require2.logger;

var RuntimeManager = function () {
  function RuntimeManager() {
    (0, _classCallCheck3.default)(this, RuntimeManager);

    this.runtimeTerminalMap = {};
  }

  (0, _createClass3.default)(RuntimeManager, [{
    key: "connect",
    value: function connect(channelId) {
      var _this = this;

      return new _promise2.default(function (resolve, reject) {
        request.getRemote("http://127.0.0.1:" + (config.REMOTE_DEBUG_PORT || 9222) + "/json").then(function (data) {
          var list = JSON.parse(data);
          var found = false;
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3.default)(list), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var target = _step.value;

              var urlObj = URL.parse(target.url);
              if (urlObj.pathname === "/runtime.html" && urlObj.port === config.port + "") {
                found = target;
                break;
              } else if (urlObj.pathname === "/debug.html") {
                found = target;
              }
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator.return) {
                _iterator.return();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }

          if (found) {
            if (found.webSocketDebuggerUrl) {
              logger.verbose("Have found the webSocketDebuggerUrl: " + found.webSocketDebuggerUrl);
              var ws = new WebSocket(found.webSocketDebuggerUrl);
              var terminal = new WebsocketTerminal(ws, channelId);
              var _runtimeTerminalMaps = _this.runtimeTerminalMap[channelId];
              if (_runtimeTerminalMaps && _runtimeTerminalMaps.length > 0) {
                _runtimeTerminalMaps.unshift(terminal);
              } else {
                _this.runtimeTerminalMap[channelId] = [terminal];
              }
              resolve(terminal);
            } else {
              logger.verbose("Not found the webSocketDebuggerUrl from the " + found);
              reject("TOAST_DO_NOT_OPEN_CHROME_DEVTOOL");
            }
          } else {
            logger.verbose("Not found the remote debug json");
            reject("TOAST_CAN_NOT_FIND_RUNTIME");
          }
        }).catch(function (e) {
          reject("TOAST_JS_RUNTIME_INIT_FAIL");
        });
      });
    }
  }, {
    key: "remove",
    value: function remove(channelId) {
      var terminals = this.runtimeTerminalMap[channelId];
      if (terminals && terminals.length > 0) {
        var popTerminal = terminals.pop();
        popTerminal.websocket.close();
      } else {
        logger.error(new Error("Try to remove a non-exist runtime"));
      }
    }
  }, {
    key: "has",
    value: function has(channelId) {
      var terminals = this.runtimeTerminalMap[channelId];
      return terminals && terminals.length > 0;
    }
  }]);
  return RuntimeManager;
}();

module.exports = new RuntimeManager();