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} /> : null;

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

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

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

    },

});

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()
  };
}


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