import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { PureComponent, createRef } from 'react';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
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() {
    super(...arguments);
    _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__*/_jsxs("pre", {
      className: classNames(baseClassName, {
        [`${baseClassName}--wide`]: wide
      }, className),
      ref: this.rootRef,
      onScroll: onScroll,
      ...props,
      children: [children, cursor ? /*#__PURE__*/_jsx("span", {
        className: `${baseClassName}__cursor`
      }) : null]
    });
  }
}
_defineProperty(ConsoleOutput, "defaultProps", {
  baseClassName: `${CLS_PREFIX}console-output`,
  wide: false,
  cursor: false,
  autoscroll: true
});
export default ConsoleOutput;