import React from "react"
import cytoscape from "cytoscape"
import {DEF_VISUAL_STYLE} from "./VisualStyle"

// TODO: consolidate Cytoscape-dependent tags
const CYTOSCAPE_TAG = 'cy';

// Original position will be used when layout is positions are available
const DEF_LAYOUT = 'preset';

// Layout to be used when there is no layout information
const DEF_NO_LAYOUT = 'cose';

const CYJS_SELECT = 'select';


/**
 * Simple Network Viewer Component
 */
class CytoscapeRenderer extends React.Component {

  constructor(props) {
    super(props);
  }

  updateCyjs() {

    console.log('* Cytoscape.js is rendering new network...');
    console.log(this.props)

    let visualStyle = this.props.graph.style
    let layout = DEF_LAYOUT

    if(visualStyle === undefined || visualStyle === null) {
      visualStyle = DEF_VISUAL_STYLE
      layout = DEF_NO_LAYOUT
    }

    this.cy = cytoscape({

      container: document.getElementById(CYTOSCAPE_TAG),
      elements: this.props.graph.elements,
      style: visualStyle,
      layout: {
        name: layout
      }

    });

    this.setEventListener()
  }

  setEventListener() {
    // TODO: Add support for more event types
    this.cy.on('data select unselect add remove', (ev) => {
        if (ev.originalEvent.type === CYJS_SELECT) {
          let selected = ev.cyTarget;
          this.handleSelect(selected)
        }
      }
    )
  }

  /**
   * Select event handler
   *
   * @param selected
   */
  handleSelect(selected) {
    this.props.cyjsSelected(selected)
  }

  /**
   * Once "cy" is ready, draw network calling raw Cytoscape.js API.
   */
  componentDidUpdate() {
    this.updateCyjs();
  }

  componentWillReceiveProps(nextProps) {
    // Check next prop contains new network location or not:
    if (nextProps.graphUrl !== this.props.graphUrl) {
      console.log("------ New Network Location Found! ----");
      this.props.fetchNetwork(nextProps.graphUrl);
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextProps.graph === this.props.graph && nextProps.graphUrl === this.props.graphUrl) {
      console.log("@No need to update view...");
      return false;
    }
    return true;
  }

  render() {
    return (
      <div class="network-widget">
        <div id={CYTOSCAPE_TAG} style={this.props.style}></div>
      </div>
    )
  }
}

export default CytoscapeRenderer
