import React from 'react';
import Fluky from 'fluky';

var DragSource = require('react-dnd').DragSource;

var ItemTypes = {
	group: 'digital'
};

var componentSource = {
	beginDrag: function (props) {
		var item = {
			sku: props.sku,
			name: props.name,
			color: props.color,
			border: props.border,
			image: props.image,
			pins: props.pins,
			tips: props.tips,
			usePorts: props.usePorts,
			samples: props.samples
		};

		return item;
	},
	endDrag: function (props, monitor, component) {
		var item = monitor.getItem();
		var dropResult = monitor.getDropResult();

		Fluky.dispatch('action.Tips.setTips', item.tips, item.samples);
		
		if (dropResult) {
			var itemName = item.name;
			// console.log(item);
			Fluky.dispatch('action.WorkBoard.connectModule', item.sku, dropResult.pin);
		}
	}
};

function collect(connect, monitor) {
	return {
		connectDragSource: connect.dragSource(),
		isDragging: monitor.isDragging()
	};
}

class Components extends React.Component {
	constructor() {
		super();

		var builder = Fluky.getState('Builder');
		var displayModules = Fluky.getState('WorkBoard').displayModules;

		this.state = {
			'displayModules': displayModules
		};
	}

	componentWillMount() {
		Fluky.on('store.WorkBoard.displayModule', Fluky.bindListener(this.onChange));
	}

	componentWillUnmount() {
		Fluky.off('store.WorkBoard.displayModule', this.onChange);
	}

	onChange = () => {
		var displayModules = Fluky.getState('WorkBoard').displayModules;

		this.setState({
			'displayModules': displayModules
		});
	}

	render() {
		var sku = this.props.sku;
		var image = this.props.image;
		var name = this.props.name;
		var color = this.props.color;
		var io = this.props.io;
	    var isDragging = this.props.isDragging;
	    var connectDragSource = this.props.connectDragSource;
	    var displayModules = this.state.displayModules;

		if (displayModules) {
		    if (displayModules[sku]) {
		    	return null;
		    }
		}

		return connectDragSource(
			<div className={'component'}>
				<div className={'row'}>
					<div className={'col s6'}>
						<div className="sensor-image" style={{ backgroundImage: 'url(' + image + ')' }}></div>
					</div>
					<div className={'col s6 remove-padding'}>
						<p className={'component-name'}>{ name }</p>
						<div className={ 'squre ' + color }>
						<p className={'io'}>{ io }</p>
						</div>
					</div>
				</div>
			</div>
		);
	};
}

module.exports = DragSource(ItemTypes.group, componentSource, collect)(Components);
