import React, { useEffect } from 'react';
import GraphinContext from '../GraphinContext';

var DragNodeWithForce = function DragNodeWithForce(props) {
  var _React$useContext = React.useContext(GraphinContext),
      graph = _React$useContext.graph,
      layout = _React$useContext.layout;

  var autoPin = props.autoPin;
  var instance = layout.instance;
  useEffect(function () {
    var simulation = instance.simulation,
        type = instance.type;

    var handleNodeDragStart = function handleNodeDragStart() {
      console.log('drag-start', instance);

      if (simulation) {
        simulation.stop();
      }
    };

    var handleNodeDragEnd = function handleNodeDragEnd(e) {
      if (type !== 'graphin-force') {
        return;
      }

      if (e.item) {
        var nodeModel = e.item.get('model');
        nodeModel.x = e.x;
        nodeModel.y = e.y;
        nodeModel.layout = Object.assign(Object.assign({}, nodeModel.layout), {
          force: {
            mass: autoPin ? 1000000 : null
          }
        });
        var drageNodes = [nodeModel];
        simulation.restart(drageNodes, graph);
        graph.refreshPositions();
      }
    };

    graph.on('node:dragstart', handleNodeDragStart);
    graph.on('node:dragend', handleNodeDragEnd);
    return function () {
      graph.off('node:dragstart', handleNodeDragStart);
      graph.off('node:dragend', handleNodeDragEnd);
    };
  }, [graph, autoPin, instance]);
  return null;
};

export default DragNodeWithForce;