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

/* eslint-disable react/no-did-mount-set-state */
import React, { Component, createRef } from 'react';
import classNames from 'classnames';
import Measure from 'react-measure';
import { CLS_PREFIX } from '../../constants';
import Translate from '../Translate';
import Link from '../Link';

/**
 * `Cuttable` component is used for showing and hiding part of content.
 * @since 0.0.42
 */
class Cuttable extends Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "state", {
      collapsed: undefined,
      autofit: true
    });

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

    _defineProperty(this, "handleToggle", () => {
      this.setState(({
        collapsed
      }) => ({
        collapsed: !collapsed,
        autofit: false
      }));
    });

    _defineProperty(this, "handleResize", () => {
      if (!this.state.autofit) {
        return;
      }

      const content = this.contentRef.current;

      if (content && content.scrollHeight > content.clientHeight) {
        this.setState({
          collapsed: this.props.collapsed
        });
      }
    });
  }

  render() {
    const {
      baseClassName,
      className,
      children,
      collapsed,
      maxHeight,
      locale,
      ...props
    } = this.props;
    const showMoreLessKey = this.state.collapsed ? 'showMore' : 'showLess';
    return /*#__PURE__*/React.createElement("div", _extends({
      className: classNames(baseClassName, {
        [`${baseClassName}--collapse`]: this.state.collapsed === true,
        [`${baseClassName}--expand`]: this.state.collapsed === false
      }, className)
    }, props), /*#__PURE__*/React.createElement(Measure, {
      onResize: this.handleResize,
      innerRef: el => {
        this.contentRef.current = el;
      }
    }, ({
      measureRef
    }) => /*#__PURE__*/React.createElement("div", {
      className: `${baseClassName}__content`,
      style: {
        maxHeight
      },
      ref: measureRef
    }, children)), this.state.collapsed !== undefined && /*#__PURE__*/React.createElement("div", {
      className: `${baseClassName}__action`
    }, /*#__PURE__*/React.createElement(Link, {
      onClick: this.handleToggle
    }, /*#__PURE__*/React.createElement(Translate, {
      content: `Cuttable.${showMoreLessKey}`,
      fallback: locale[showMoreLessKey]
    }))));
  }

}

_defineProperty(Cuttable, "defaultProps", {
  collapsed: true,
  maxHeight: '7rem',
  locale: {
    showMore: 'Show more',
    showLess: 'Show less'
  },
  baseClassName: `${CLS_PREFIX}cuttable`
});

export default Cuttable;