import React from 'react';
import { WarningWrapper } from '../StyledWrappers';
import { UploadFieldWrapper } from './StyledWrappers';
import shortid from 'shortid';
import * as UploadVariants from './ImagePreviewWidget';

class Upload extends React.Component {
	static get propTypes() {
        return {
            showFileNames: React.PropTypes.bool,
            accept: React.PropTypes.string,
            multiple: React.PropTypes.bool,
            disabled: React.PropTypes.bool,
            error: React.PropTypes.bool,
            onChange: React.PropTypes.func,
            className: React.PropTypes.string,
            warningClassName: React.PropTypes.string
        };
    }

	constructor(props) {
		super(props);
		this.state = {
			files: null,
			id:shortid.generate()
		};
		this.handleUpload = this.handleUpload.bind(this);
	}	

	getFileNames(files) {
		let fileNames = [];
		for(var i=0; i<files.length; i++) {
			fileNames.push(files[i].name);
		}
		return fileNames.join(', ');
	}

	handleUpload = (event) => {
		var files = event.target.files;   
		var uploadedFileNames = this.getFileNames(files);
		this.setState({	files, uploadedFileNames }, () => {
			if(this.props.onChange) {
				this.props.onChange(files);
			}
		});
	}

	render() {
		const { classes } = this.props;
		return(
			<UploadFieldWrapper className={this.props.className}>
				<input
					type="file"
					onChange={this.handleUpload}
					className="input"
					multiple={this.props.multiple}
					accept={this.props.accept}
					disabled={this.props.disabled}
					name={this.state.id}
					id={this.state.id}
					accept={this.props.accept||"image/*"}				
				/>				
				<label 
					className={`upload-icon ${this.props.error ? 'error' : ''} ${this.state.files && this.state.files.length ? 'uploaded' : ''} ${this.props.disabled ? 'disabled' : ''}`} 
					htmlFor={this.state.id}
					title={this.state.uploadedFileNames}
				>
                	<i className="material-icons">cloud_upload</i>
                	{this.props.showFileNames && <span className="uploaded-files">{this.state.uploadedFileNames}</span>}
                </label>
                {this.props.warning && <WarningWrapper className={this.props.warningClassName}>{this.props.warning}</WarningWrapper>}
			</UploadFieldWrapper>
		)
	}
}

module.exports = {
	Upload,
	...UploadVariants

}
