var _class, _class2, _temp;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * THIS FILE IS PART OF Choerodon PROJECT
 * Term.js - base on xterm.js
 */
import React, { PureComponent } from 'react';
import { Terminal } from 'xterm';
import _ from 'lodash';
import { injectIntl } from 'react-intl';
import { Choerodon } from '@choerodon/boot';
import * as fit from 'xterm/lib/addons/fit/fit';
import * as attach from 'xterm/lib/addons/attach/attach';
import 'xterm/dist/xterm.css';
import "./Term.less"; // 添加插件

Terminal.applyAddon(fit);
Terminal.applyAddon(attach);

var Term = injectIntl(_class = (_temp = _class2 = /*#__PURE__*/function (_PureComponent) {
  _inherits(Term, _PureComponent);

  var _super = _createSuper(Term);

  function Term() {
    var _this;

    _classCallCheck(this, Term);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.term = null;
    _this.socket = null;
    _this.resizeScreen = _.debounce(function () {
      if (_this.term) {
        _this.term.fit();

        var _this$term = _this.term,
            cols = _this$term.cols,
            rows = _this$term.rows;

        _this.term.resize(cols, rows);
      }
    }, 100);

    _this.runRealTerminal = function () {
      _this.term.clear();

      _this.term.setOption('disableStdin', false);

      _this.term.attach(_this.socket, false);

      _this.term.dataListener = _this.term.onData(function (data) {
        _this.socket.send(new Blob([data], {
          type: 'text/plain'
        }));
      });
      _this.term._initialized = true;
    };

    _this.stopTerminal = function () {
      var intl = _this.props.intl;

      if (_this.term) {
        _this.term.write(intl.formatMessage({
          id: 'devops.term.close'
        }));

        _this.term.writeln('');

        _this.term.setOption('disableStdin', true);
      }
    };

    _this.errorTerminal = function () {
      var intl = _this.props.intl;

      if (_this.term) {
        _this.term.write(intl.formatMessage({
          id: 'devops.term.error'
        }));

        _this.term.writeln('');

        _this.term.setOption('disableStdin', true);
      } else {
        Choerodon.prompt(intl.formatMessage({
          id: 'devops.term.error'
        }));
      }
    };

    return _this;
  }

  _createClass(Term, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setupTerm();
      window.addEventListener('resize', this.resizeScreen, false);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.socket) {
        this.socket.close();
      }

      this.term = null;
      this.socket = null;
      window.removeEventListener('resize', this.resizeScreen);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState, snapshot) {
      var _this2 = this;

      if (this.props.id !== prevProps.id || this.props.url !== prevProps.url) {
        if (!this.term) {
          this.setupTerm();
        } else {
          try {
            this.term.detach(this.socket);
          } catch (e) {
            console.log(e);
          } finally {
            this.term.dataListener.dispose();
            this.term.dataListener = undefined;

            if (this.socket) {
              this.socket.close();
              this.socket = null;
            }

            setTimeout(function () {
              _this2.createConnect();
            }, 0);
          }
        }
      }
    }
  }, {
    key: "setupTerm",
    value: function setupTerm() {
      var _this3 = this;

      var terminalContainer = document.getElementById('c7n-devops-terminal');

      while (terminalContainer && terminalContainer.children.length) {
        terminalContainer.removeChild(terminalContainer.children[0]);
      }

      var term = new Terminal({
        // rendererType: 'dom',
        bellStyle: 'sound'
      });
      this.term = term;
      term.open(terminalContainer);
      term.fit();
      term.focus();
      setTimeout(function () {
        if (!_this3.socket) {
          _this3.createConnect();
        }
      }, 0);
    }
  }, {
    key: "createConnect",
    value: function createConnect() {
      var url = this.props.url;

      try {
        var socket = new WebSocket(url);
        this.socket = socket;
        socket.onopen = this.runRealTerminal;
        socket.onclose = this.stopTerminal;
        socket.onerror = this.errorTerminal;
      } catch (e) {
        this.errorTerminal();
        throw new Error("Failed to construct 'WebSocket': The URL ERROR");
      }
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement("div", {
        className: "c7n-devops-terminal",
        id: "c7n-devops-terminal"
      });
    }
  }]);

  return Term;
}(PureComponent), _class2.defaultProps = {
  id: ''
}, _temp)) || _class;

export { Term as default };