import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/lib/select/style";
import _Select from "choerodon-ui/lib/select";
import "choerodon-ui/lib/modal/style";
import _Modal from "choerodon-ui/lib/modal";

var _dec, _class;

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 _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); }

/* eslint-disable no-underscore-dangle */
import React, { Component, Fragment } from 'react';
import _ from 'lodash';
import { observer, inject } from 'mobx-react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Content } from '@choerodon/boot';
import ReactCodeMirror from 'react-codemirror';
import uuidv1 from 'uuid/v1';
import Cookies from 'universal-cookie';
import { removeEndsChar } from "../../utils";
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/base16-dark.css';
import "./index.less";
var LOG_OPTIONS = {
  readOnly: true,
  lineNumbers: true,
  lineWrapping: true,
  autofocus: true,
  theme: 'base16-dark'
};
var Sidebar = _Modal.Sidebar;
var Option = _Select.Option;
var cookies = new Cookies();

var getAccessToken = function getAccessToken() {
  return cookies.get('access_token');
};

var LogSidebar = (_dec = inject('AppState'), _dec(_class = injectIntl(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(LogSidebar, _Component);

  var _super = _createSuper(LogSidebar);

  function LogSidebar(props) {
    var _this;

    _classCallCheck(this, LogSidebar);

    _this = _super.call(this, props);

    _this.handleChange = function (value) {
      var _value$split = value.split('+'),
          _value$split2 = _slicedToArray(_value$split, 2),
          logId = _value$split2[0],
          containerName = _value$split2[1]; // eslint-disable-next-line react/destructuring-assignment


      if (logId !== _this.state.logId) {
        _this.setState({
          containerName: containerName,
          logId: logId
        });

        _this.clearLogAndTimer();

        setTimeout(function () {
          return _this.loadLog(false);
        }, 500);
      }
    };

    _this.clearLogAndTimer = function () {
      clearInterval(_this.timer);
      _this.timer = null;

      if (_this.socket) {
        _this.socket.close();
      }

      _this.socket = null;
    };

    _this.goTop = function () {
      var editor = _this.editorLog.getCodeMirror();

      editor.execCommand('goDocStart');
    };

    _this.stopFollowing = function () {
      if (_this.socket) {
        _this.socket.close();
      }

      if (_this.timer) {
        clearInterval(_this.timer);
        _this.timer = null;
      }

      _this.setState({
        following: false
      });
    };

    _this.setFullScreen = function () {
      var cm = _this.editorLog.getCodeMirror();

      var wrap = cm.getWrapperElement();
      cm.state.fullScreenRestore = {
        scrollTop: window.pageYOffset,
        scrollLeft: window.pageXOffset,
        width: wrap.style.width,
        height: wrap.style.height
      };
      wrap.style.width = '';
      wrap.style.height = 'auto';
      wrap.className += ' CodeMirror-fullScreen';

      _this.setState({
        fullScreen: true
      });

      document.documentElement.style.overflow = 'hidden';
      cm.refresh();
      window.addEventListener('keydown', function (e) {
        _this.setNormal(e.which);
      });
    };

    _this.setNormal = function () {
      if (!_this.editorLog) return;

      var cm = _this.editorLog.getCodeMirror();

      var wrap = cm.getWrapperElement();
      wrap.className = wrap.className.replace(/\s*CodeMirror-fullScreen\b/, '');

      _this.setState({
        fullScreen: false
      });

      document.documentElement.style.overflow = '';
      var info = cm.state.fullScreenRestore;
      wrap.style.width = info.width;
      wrap.style.height = info.height;
      window.scrollTo(info.scrollLeft, info.scrollTop);
      cm.refresh();
      window.removeEventListener('keydown', function (e) {
        _this.setNormal(e.which);
      });
    };

    _this.loadLog = function () {
      var isFollow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var _this$props = _this.props,
          record = _this$props.record,
          propsClusterId = _this$props.clusterId,
          propsProjectId = _this$props.projectId,
          currentProjectId = _this$props.AppState.currentMenuType.projectId;

      var _ref = record || {},
          namespace = _ref.namespace,
          name = _ref.name,
          recordPodName = _ref.podName;

      var clusterId = propsClusterId || (record === null || record === void 0 ? void 0 : record.clusterId);
      var projectId = propsProjectId || currentProjectId || (record === null || record === void 0 ? void 0 : record.projectId);
      var podName = name || recordPodName;
      var _this$state = _this.state,
          logId = _this$state.logId,
          containerName = _this$state.containerName,
          following = _this$state.following;
      var wsUrl = removeEndsChar(window._env_.DEVOPS_HOST, '/');
      var secretKey = window._env_.DEVOPS_WEBSOCKET_SECRET_KEY;
      var key = "cluster:".concat(clusterId, ".log:").concat(uuidv1());
      var url = "".concat(wsUrl, "/websocket?key=").concat(key, "&group=from_front:").concat(key, "&processor=front_log&secret_key=").concat(secretKey, "&env=").concat(namespace, "&podName=").concat(podName, "&containerName=").concat(containerName, "&logId=").concat(logId, "&clusterId=").concat(clusterId, "&oauthToken=").concat(getAccessToken(), "&projectId=").concat(projectId);
      var logs = [];
      var oldLogs = [];
      var editor = null;

      if (_this.editorLog) {
        editor = _this.editorLog.getCodeMirror();

        try {
          var ws = new WebSocket(url);

          _this.setState({
            following: true
          });

          if (!isFollow) {
            editor.setValue('Loading...\n');
          }

          ws.onopen = function () {
            editor.setValue('Loading...\n');
          };

          ws.onerror = function (e) {
            if (_this.timer) {
              clearInterval(_this.timer);
              _this.timer = null;
            }

            logs.push('\n连接出错，请重新打开\n');
            editor.setValue(_.join(logs, ''));
            editor.execCommand('goDocEnd');
          };

          ws.onclose = function () {
            if (_this.timer) {
              clearInterval(_this.timer);
              _this.timer = null;
            }

            if (following) {
              logs.push('\n连接已断开\n');
              editor.setValue(_.join(logs, ''));
            }

            editor.execCommand('goDocEnd');
          };

          ws.onmessage = function (e) {
            if (e.data.size) {
              var reader = new FileReader();
              reader.readAsText(e.data, 'utf-8');

              reader.onload = function () {
                if (reader.result !== '') {
                  logs.push(reader.result);
                }
              };
            }

            if (!logs.length) {
              var logString = _.join(logs, '');

              editor.setValue(logString);
            }
          };

          _this.socket = ws;
          _this.timer = setInterval(function () {
            if (logs.length > 0) {
              if (!_.isEqual(logs, oldLogs)) {
                var logString = _.join(logs, '');

                editor.setValue(logString);
                editor.execCommand('goDocEnd'); // 如果没有返回数据，则不进行重新赋值给编辑器

                oldLogs = _.cloneDeep(logs);
              }
            } else if (!isFollow) {
              editor.setValue('Loading...\n');
            }
          }, 0);
        } catch (e) {
          editor.setValue('连接失败\n');
          throw new Error("Failed to construct 'WebSocket': The URL ERROR");
        }
      }
    };

    _this.state = {
      following: true,
      fullScreen: false,
      containerName: '',
      logId: null
    };
    _this.timer = null;
    _this.socket = null;
    return _this;
  }

  _createClass(LogSidebar, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      var _this$props$record = this.props.record,
          containers = _this$props$record.containers,
          containerIndex = _this$props$record.containerIndex;
      var _containers = containers[containerIndex || 0],
          name = _containers.name,
          logId = _containers.logId;
      this.setState({
        containerName: name,
        logId: logId
      });
      setTimeout(function () {
        return _this2.loadLog(false);
      }, 500);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.clearLogAndTimer();
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props2 = this.props,
          visible = _this$props2.visible,
          onClose = _this$props2.onClose,
          containers = _this$props2.record.containers;
      var _this$state2 = this.state,
          following = _this$state2.following,
          fullScreen = _this$state2.fullScreen,
          containerName = _this$state2.containerName;

      var containerOptions = _.map(containers, function (container) {
        var logId = container.logId,
            name = container.name;
        return /*#__PURE__*/React.createElement(Option, {
          key: logId,
          value: "".concat(logId, "+").concat(name)
        }, name);
      });

      return /*#__PURE__*/React.createElement(Sidebar, {
        visible: visible,
        title: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "log.header.title"
        }),
        onOk: onClose,
        className: "c7n-container-sidebar c7n-region",
        okText: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "close"
        }),
        okCancel: false
      }, /*#__PURE__*/React.createElement(Content, {
        className: "sidebar-content"
      }, /*#__PURE__*/React.createElement("div", {
        className: fullScreen ? 'c7n-container-sidebar-content_full' : 'c7n-container-sidebar-content'
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7n-term-title"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "container"
      }), "\xA0", /*#__PURE__*/React.createElement(_Select, {
        className: "c7n-log-siderbar-select",
        value: containerName,
        onChange: this.handleChange
      }, containerOptions), /*#__PURE__*/React.createElement(_Button, {
        className: "c7n-term-fullscreen",
        color: "primary",
        funcType: "flat",
        shape: "circle",
        icon: "fullscreen",
        onClick: this.setFullScreen
      })), /*#__PURE__*/React.createElement("div", {
        className: "c7n-podLog-action c7n-term-following ".concat(fullScreen ? 'c7n-term-following_full' : ''),
        onClick: following ? this.stopFollowing : this.loadLog,
        role: "none"
      }, following ? 'Stop Following' : 'Start Following'), /*#__PURE__*/React.createElement("div", {
        className: "c7n-term-wrap"
      }, /*#__PURE__*/React.createElement(ReactCodeMirror, {
        ref: function ref(editor) {
          _this3.editorLog = editor;
        },
        value: "Loading...",
        className: "c7n-log-editor",
        options: LOG_OPTIONS
      })), /*#__PURE__*/React.createElement("div", {
        className: "c7n-podLog-action c7n-term-totop ".concat(fullScreen ? 'c7n-term-totop_full' : ''),
        onClick: this.goTop,
        role: "none"
      }, "Go Top"))));
    }
  }]);

  return LogSidebar;
}(Component)) || _class) || _class) || _class);
export { LogSidebar as default };