/**
 * Support Form Component to focus when inline errors happen and guarantee focus order.
 * @param {*} Component
 */
'use strict';

import React from 'react';
import PropTypes from 'prop-types';

type FormErrorAutoFocusContainerProps = {
    children?: React.ReactNode;
    testAutomationId?: string;
};

export class FormErrorAutoFocusContainer extends React.Component<FormErrorAutoFocusContainerProps> {
    static propTypes: any = {
        children: PropTypes.node,
        testAutomationId: PropTypes.string
    };

    static defaultProps = {
        children: null,
        testAutomationId: null
    };

    static contextTypes = {
        getNeededAutoFocus: PropTypes.func,
        setNeededAutoFocus: PropTypes.func
    };

    static childContextTypes = {
        getNeededAutoFocus: PropTypes.func,
        setNeededAutoFocus: PropTypes.func
    };

    isNeededAutoFocus: boolean;

    constructor(props, context) {
        super(props, context);
        this.isNeededAutoFocus = false;
    }

    getChildContext() {
        return {
            setNeededAutoFocus: this.context.setNeededAutoFocus || this.setNeededAutoFocus,
            getNeededAutoFocus: this.context.getNeededAutoFocus || this.getNeededAutoFocus
        };
    }

    getNeededAutoFocus = () => this.isNeededAutoFocus;

    /**
     * Set isNeededAutoFocus to 'true' when Form need focus.
     * @param {boolean} value
     */
    setNeededAutoFocus = value => {
        this.isNeededAutoFocus = value;
    };

    render() {
        const children = this.props.children;
        if (!children) {
            return null;
        }
        if (Array.isArray(children)) {
            return <div data-test-automation-id={this.props.testAutomationId}>{children}</div>;
        }
        return children;
    }
}
