import PropTypes from 'prop-types';
import React from 'react';
import './index.css';

const UserCounter = React.createClass({

    _renderItem(item, index) {
        if (!item || !item.getAvatar) {
            return <div className="ui-user-counter__item ui-user-counter__item_empty" />;
        }

        return (
            <div className="ui-user-counter__item" key={index} title={item.getName()}>
                <img src={item.getAvatar()} className="ui-user-counter__item-image" />
            </div>
        );
    },

    _renderItems() {
        const { items, maxCount } = this.props;

        if (!items || !items.length) {
            return null;
        }

        return (
            <div className="ui-user-counter__items">
                {items.slice(0, maxCount).map(this._renderItem)}
            </div>
        );
    },

    _renderCounter() {
        const { items, maxCount } = this.props;
        const restCount = items.length - maxCount;

        if (!items || !items.length || restCount < 1) {
            return null;
        }

        return (
            <div className="ui-user-counter__counter">
                +{restCount}
            </div>
        );
    },

    _renderValue() {
        return (
            <div className="ui-user-counter__total">
                {this.props.value || this.props.items.length}
            </div>
        );
    },

    _renderControls() {
        const { editable, onAddClick } = this.props;

        if (!editable) {
            return null;
        }

        return (
            <div className="ui-user-counter__controls">
                <div className="ui-user-counter__add" onClick={onAddClick} />
            </div>
        );
    },

    render() {
        const { items } = this.props;
        const className = [
            'ui-user-counter',
            items && items.length ? null : 'ui-user-counter_empty',
        ].filter(Boolean).join(' ');

        return (
            <div className={className} onClick={this.props.onClick}>
                {this._renderValue()}
                {this._renderControls()}
                {this._renderItems()}
                {this._renderCounter()}
            </div>
        );
    },

});

// @if NODE_ENV='development'
UserCounter.propTypes = {
    items: PropTypes.array,
    size: PropTypes.oneOf(['s', 'm', 'l']),
    maxCount: PropTypes.number,
};
// @endif

UserCounter.defaultProps = {
    items: [],
    size: 'm',
    maxCount: 5,
};

export default UserCounter;
