import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';

import Item from './Item';
import Navigation from './Navigation';

import './index.css';

function toArray(x) {
    if (!x) {
        return [];
    }

    return x.toArray ? x.toArray() : [x];
}

function indexElements(elements) {
    return React.Children.map(elements, (element, index) => React.cloneElement(element, { ref: index }));
}

const Slider = React.createClass({

    getInitialState() {
        return {
            index: this.props.index,
            size: toArray(this.props.children).length,
        };
    },

    componentWillReceiveProps(nextProps) {
        this.setState(_.pick(nextProps, ['index', 'size']));
    },

    componentDidUpdate() {
        this._postrender();
    },

    _postrender() {
        for (let i = 0; i < this.state.size; i++) {
            const element = ReactDOM.findDOMNode(this.refs[i]);

            if (element) {
                if (i === this.state.index) {
                    element.classList.add('slide_active');
                } else {
                    element.classList.remove('slide_active');
                }
            }
        }
    },

    render() {
        return (
            <div className={this.props.className} ref={this._postrender}>
                {indexElements(this.props.children)}
            </div>
        );
    },

});

Slider.Item = Item;
Slider.Navigation = Navigation;

// @if NODE_ENV='development'
Slider.propTypes = {
    className: PropTypes.string,
    items: PropTypes.array,
    index: PropTypes.number,
};
// @endif

Slider.defaultProps = {
    className: 'slider',
    items: [],
    index: 0,
};

export default Slider;
