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, { Component, Children, isValidElement } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { CLS_PREFIX } from '../../constants';
import { safeInvoke } from '../utils';
import { STATUS_NOT_STARTED, STATUS_RUNNING, STATUS_DONE, STATUS_ERROR } from '../ProgressStep';

/**
 * `Progress` is used for showing progress of performing long operations.
 * @since 1.10.0
 */
class Progress extends Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "state", {
      status: null
    });
  }

  static getDerivedStateFromProps({
    children
  }) {
    let isNotStarted = true;
    let isFinished = true;
    let isFailed = false;

    if (children) {
      Children.forEach(children, child => {
        if ( /*#__PURE__*/isValidElement(child) && child.props.status) {
          isNotStarted = isNotStarted && child.props.status === STATUS_NOT_STARTED;
          isFinished = isFinished && child.props.status === STATUS_DONE;
          isFailed = isFailed || child.props.status === STATUS_ERROR;
        }
      });
    }

    if (isFinished) {
      return {
        status: STATUS_DONE
      };
    }

    if (isNotStarted) {
      return {
        status: STATUS_NOT_STARTED
      };
    }

    if (isFailed) {
      return {
        status: STATUS_ERROR
      };
    }

    return {
      status: STATUS_RUNNING
    };
  }

  componentDidMount() {
    const {
      status
    } = this.state;
    const {
      onStatusChange
    } = this.props;
    safeInvoke(onStatusChange, status);
  }

  componentDidUpdate(prevProps, prevState) {
    const {
      status
    } = this.state;
    const {
      onStatusChange
    } = this.props;

    if (prevState.status !== status) {
      safeInvoke(onStatusChange, status);
    }
  }

  render() {
    const {
      baseClassName,
      className,
      children,
      onStatusChange,
      ...props
    } = this.props;
    return /*#__PURE__*/React.createElement("div", _extends({
      className: classNames(baseClassName, className)
    }, props), children);
  }

}

Progress.propTypes = {
  /**
   * On overall status event handler.
   * @since 1.10.0
   */
  onStatusChange: PropTypes.func,

  /**
   * Content of the `Progress`.
   * @since 1.10.0
   */
  children: PropTypes.node,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * @ignore
   */
  baseClassName: PropTypes.string
};
Progress.defaultProps = {
  onStatusChange: null,
  children: null,
  className: null,
  baseClassName: "".concat(CLS_PREFIX, "progress")
};
export default Progress;