/**
 * Component for displaying a group of inputs (input, select, date Input, number Input, buttons) in a string.
 * Changes display styles by removing rounding between elements
 *
 * @author Brauer Ilya
 *
 * @date 2020-05-06
 */

import * as React from 'react';

import * as styles from './groupInput.m.scss';
import {joinClassNames} from '../../utils/joinClassNames';
import {GroupItem} from './GroupItem';
import {Wrapper} from '../wrapper/Wrapper';

interface IGroupInputProps {
    isDivided?: boolean;
    widthMap?: { [key: number]: React.CSSProperties['width'] };
    onBlur?: () => void;
}

export class GroupInput extends React.Component<IGroupInputProps> {

    get listOfExistChild () {
        const Child: React.ReactNode[] = [];

        React.Children.forEach(this.props.children, (child) => {
            if (child) {
                Child.push(child);
            }
        });

        return Child;
    }

    override render () {
        const className = joinClassNames(styles.groupContainer, [styles.isDivided, Boolean(this.props.isDivided)]);
        const childrenLastIndex = this.listOfExistChild.length - 1;

        return (
            <Wrapper onClickOutside={this.props.onBlur} transparent={true}>
                <div className={className}>
                    {React.Children.map(this.listOfExistChild, (child,  index) => {
                        const widthMap = this.props.widthMap;
                        const width = widthMap && widthMap[index] ? widthMap[index] : undefined;

                        return (
                            <GroupItem
                                index={index}
                                isFirst={index === 0}
                                isLast={index === childrenLastIndex}
                                width={width}>
                                {child}
                            </GroupItem>
                        );
                    })}
                </div>
            </Wrapper>
        );
    }
}
