import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { PureComponent, createRef } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';

const scrollToBottom = el => {
  el.scrollTop = el.scrollHeight;
};

/**
 * `ConsoleOutput` component is used for showing dynamically updating data from console output.
 * @since 0.0.35
 */
class ConsoleOutput extends PureComponent {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "rootRef", /*#__PURE__*/createRef());

    _defineProperty(this, "prevScrollTop", 0);

    _defineProperty(this, "autoscrollCancelled", false);

    _defineProperty(this, "handleScroll", () => {
      const el = this.rootRef.current;

      if (!el) {
        return;
      }

      if (el.scrollTop < this.prevScrollTop) {
        this.autoscrollCancelled = true;
      } else if (el.clientHeight + el.scrollTop >= el.scrollHeight) {
        this.autoscrollCancelled = false;
      }
    });
  }

  componentDidMount() {
    const {
      autoscroll
    } = this.props;
    const el = this.rootRef.current;

    if (autoscroll && el) {
      scrollToBottom(el);
    }
  }

  componentDidUpdate() {
    const {
      autoscroll
    } = this.props;
    const el = this.rootRef.current;

    if (autoscroll && el) {
      this.prevScrollTop = el.scrollTop;

      if (!this.autoscrollCancelled) {
        scrollToBottom(el);
      }
    }
  }

  render() {
    const {
      baseClassName,
      className,
      wide,
      cursor,
      children,
      autoscroll,
      ...props
    } = this.props;
    const onScroll = autoscroll ? this.handleScroll : undefined;
    return /*#__PURE__*/React.createElement("pre", _extends({
      className: classNames(baseClassName, {
        [`${baseClassName}--wide`]: wide
      }, className),
      ref: this.rootRef,
      onScroll: onScroll
    }, props), children, cursor ? /*#__PURE__*/React.createElement("span", {
      className: `${baseClassName}__cursor`
    }) : null);
  }

}

_defineProperty(ConsoleOutput, "defaultProps", {
  baseClassName: `${CLS_PREFIX}console-output`,
  wide: false,
  cursor: false,
  autoscroll: true
});

export default ConsoleOutput;