'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {FormControl} from './FormControl';
import {Radio} from 'react-bootstrap';

export class RadioControl extends FormControl<any> {
    static propTypes: any = {
        ...FormControl.propTypes,
        removeName: PropTypes.bool
    };

    static defaultProps = {
        ...FormControl.defaultProps,
        testAutomationId: 'radio',
        removeName: false
    };

    input: any;

    inputConverter(value) {
        return {
            checked: this.props.value == value, // eslint-disable-line
            value
        };
    }

    componentDidMount() {
        this.testAutomationIdHandler();
    }

    componentDidUpdate() {
        this.testAutomationIdHandler();
    }

    testAutomationIdHandler() {
        if (this.input && !this.props.hasFormGroupContainer) {
            this.input.parentNode.setAttribute(
                'data-test-automation-id',
                this.props.testAutomationId
            );
        }
    }

    getInputDOMNode() {
        return this.input;
    }

    render() {
        let {children, hiddenLabel, removeName, ...props} = this.getPropsFromContext();

        return (
            <Radio
                {...this.getSafeProps(props)}
                ref="input"
                type="radio"
                data-test-automation-id="input"
                name={removeName ? null : props.name}
                inputRef={ref => (this.input = ref)}>
                <span data-test-automation-id="label" className={!!hiddenLabel ? 'sr-only' : ''}>
                    {children}
                </span>
            </Radio>
        );
    }
}
