'use strict';

import React from 'react';
import _ from 'lodash';
import {FormControl} from './FormControl';
import {FormControl as BSFormControl} from 'react-bootstrap';
import {Static} from './Static';

export class SelectControl extends FormControl<any> {
    static propTypes: any = {
        ...FormControl.propTypes
    };

    static defaultProps = {
        ...FormControl.defaultProps,
        testAutomationId: 'select'
    };

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

        if (props.readOnly) {
            let valueStaticText = '';
            let options = _.compact(_.flatten(children as any));

            if (options.length > 0) {
                let option: any =
                    options.find((child: any) => {
                        return child.props.value == props.value; // eslint-disable-line
                    }) || options[0];

                valueStaticText = option.props.children;
            }

            return (
                <Static
                    ref="input"
                    {...this.getSafeProps(props)}
                    data-test-automation-id="select"
                    value={valueStaticText}
                    hasFeedbackBlock={false}
                />
            );
        }
        return (
            <span
                className="rc-select"
                data-test-automation-id={
                    this.props.hasFormGroupContainer ? undefined : this.props.testAutomationId
                }>
                <BSFormControl
                    ref="input"
                    data-test-automation-id="select"
                    componentClass="select"
                    {...this.getSafeProps(props)}>
                    {children}
                </BSFormControl>
            </span>
        );
    }
}
