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

import './index.css';

const FilePicker = React.createClass({

    _handlePick(event) {
        const { onPick, onRead } = this.props;
        const { files } = event.currentTarget;

        const acceptsFiles = !onPick || onPick(files);

        if (acceptsFiles && onRead) {
            const target = event.target;
            let counter = 0;

            [].forEach.call(files, file => {
                const reader = new FileReader();

                reader.onload = readerEvent => {
                    onRead(readerEvent);
                    if (++counter === files.length) {
                        // очищаем file picker для хромиум-браузеров
                        target.value = '';
                    }
                };
                reader.readAsDataURL(file);
            });
        }
    },

    render() {
        const inputProps = _.pick(this.props, ['multiple', 'accept']);
        let body = this.props.children;

        if (!body) {
            body = (
                <div className="button button_size_m button_theme_islands">
                    <span className="button__text">{this.props.text}</span>
                </div>
            );
        }

        return (
            <div className="ui-file-picker">
                {body}
                <input type="file" {...inputProps} onChange={this._handlePick} />
            </div>
        );
    },

});

// @if NODE_ENV='development'
FilePicker.propTypes = {
    multiple: PropTypes.bool,
    accept: PropTypes.string,
    text: PropTypes.string,
    onPick: PropTypes.func,
    onRead: PropTypes.func,
};
// @endif

FilePicker.defaultProps = {
    multiple: false,
};

export default FilePicker;
