import React from 'react';
import PropTypes from 'prop-types';
import isDev from '../../Utils/Dev/isDev';
import DevelopmentErrorPage from './DevelopmentErrorPage';
import ProductionErrorPage from './ProductionErrorPage';

export default class ErrorBoundary extends React.Component {
    static propTypes = {
        children: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null, info: null };
    }

    componentDidCatch(error, info) {
        this.setState({ hasError: true, error, info });
        // @todo: log the error to an error reporting service (we should create one...)
        // eslint-disable-next-line no-console
        console.error(error, info);
    }

    render() {
        if (this.state.hasError && isDev()) {
            return <DevelopmentErrorPage info={this.state.info} error={this.state.error} />;
        } else if (this.state.hasError) {
            return <ProductionErrorPage />;
        } else {
            return this.props.children;
        }
    }
}
