'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {FormControl, isIndeterminate} from './FormControl';
import Checkbox from 'react-bootstrap/lib/Checkbox';

export class CheckboxControl extends FormControl {
    static propTypes = {
        ...FormControl.propTypes,
        removeName: PropTypes.bool
    };

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

    getValue() {
        return this.getInputDOMNode().checked;
    }

    inputConverter(value) {
        return {checked: value};
    }

    outputConverter(e) {
        return e.target.checked;
    }

    getInputDOMNode() {
        return this.input;
    }

    componentWillReceiveProps(newProps) {
        this.getInputDOMNode().indeterminate = isIndeterminate(newProps.checked);
    }

    componentDidMount() {
        this.componentWillReceiveProps(this.props);
        this.testAutomationIdHandler();
    }

    componentDidUpdate() {
        this.testAutomationIdHandler();
    }

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

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

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