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

export const passedWithSelectedIdsPropsTypes = {
    selectedIds: PropTypes.object.isRequired,
    onSelectId: PropTypes.func.isRequired,
    onSelectIds: PropTypes.func.isRequired,
    onClearSelectedIds: PropTypes.func.isRequired,
    onUpdateSelectedIds: PropTypes.func.isRequired
};

export const withSelectedIds = Component => {
    return class extends React.PureComponent {
        static displayName = `WithSelectedIds(${Component.displayName ||
            Component.name ||
            'Component'})`;

        state = {
            selectedIds: {}
        };

        handleClearSelectedIds = () => {
            this.setState({selectedIds: {}});
        };

        handleUpdateSelectedIds = selectedIds => {
            this.setState({selectedIds});
        };

        handleSelectId = (id, isSelected) => {
            const selectedIds = {...this.state.selectedIds};

            if (isSelected) {
                selectedIds[id] = true;
            } else {
                delete selectedIds[id];
            }

            this.setState({selectedIds});
        };

        handleSelectIds = (ids, isSelected = true) => {
            const selectedIds = {...this.state.selectedIds};

            ids.forEach(id => {
                if (isSelected) {
                    selectedIds[id] = true;
                } else {
                    delete selectedIds[id];
                }
            });

            this.setState({selectedIds});
        };

        getSelectedIdsProps() {
            return {
                selectedIds: this.state.selectedIds,
                onSelectId: this.handleSelectId,
                onSelectIds: this.handleSelectIds,
                onClearSelectedIds: this.handleClearSelectedIds,
                onUpdateSelectedIds: this.handleUpdateSelectedIds
            };
        }

        render() {
            return <Component {...this.getSelectedIdsProps()} {...this.props} />;
        }
    };
};
