import React, { Component } from 'react';
import { DragSource } from 'react-dnd';

const boxSource = {
  beginDrag(props) {
    props.onDragStart && props.onDragStart();
    return { id: props.id, type: 'box' };
  },
  endDrag(props) {
    props.onDragEnd && props.onDragEnd();
  }
};

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

interface IProps {
  id: number;
  dragPreviewImg: string;
  connectDragPreview: Function;
  connectDragSource: Function;
  className: string;
  onDragStart: Function;
  onDragEnd: Function;
}

class DragSourceContainer extends Component<IProps> {
  componentDidMount() {
    const { dragPreviewImg, connectDragPreview } = this.props;
    const img = new Image();
    img.onload = () => {
      connectDragPreview && connectDragPreview(img);
    };
    img.src = dragPreviewImg;
  }

  render() {
    const { connectDragSource, className, children } = this.props;

    return connectDragSource(<span className={className}>{children}</span>);
  }
}

export default DragSource('box', boxSource, collect)(DragSourceContainer);
