var React = require('react/addons');
var classNames = require('classnames');
var AppIcon = require('../common/app-icon.jsx');
var DragSource = require('react-dnd').DragSource;
var DropTarget = require('react-dnd').DropTarget;
var _ = require('lodash');

var TreeItem = React.createClass({

    render: function() {

      var data = this.props.data;
      var appIcon = data.icon ? <AppIcon icon={data.icon} theme={this.props.theme} /> : null;

      var connectDragSource = this.props.connectDragSource;
      var connectDropTarget = this.props.connectDropTarget;

      var classes = classNames({
        'alert': true,
        'alert-default': !this.props.isOver,
        'alert-info': this.props.isOver && this.props.canDrop,
        'alert-success': this.props.selected
      });

      var style = {
        opacity: this.props.isDragging ? 0.5 : 1
      };

      return connectDropTarget(connectDragSource(
        <div className={classes} style={style} onClick={this.handleClick}>
          {appIcon}
          <span className="app-label">{data.label}</span>
        </div>
      ));

    },

    handleClick: function(evt) {
      evt.preventDefault();
      this.props.onItemClicked(this.props.data);
    }

});

var dragSourceSpec = {

  beginDrag: function(props) {
    return props.data;
  },

  endDrag: function(props, monitor) {

    if (!monitor.didDrop()) {
      return;
    }

    var dropResult = monitor.getDropResult();

    return props.onItemMoved(props.data, dropResult);

  }

};

var dropTargetSpec = {

  drop: function(props, monitor, component) {
    return props.data;
  },

  canDrop: function(props, monitor) {
    var draggedItem = monitor.getItem();
    return !_.isEqual(draggedItem, props.data);
  }

};

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

function dropTargetCollect(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    canDrop: monitor.canDrop()
  };
}


module.exports = DropTarget(['ITEM', 'NEW_ITEM'], dropTargetSpec, dropTargetCollect)(
  DragSource('ITEM', dragSourceSpec, dragSourceCollect)(TreeItem)
);
