import React, { useState, useEffect } from "react";

import * as cytoscape from "cytoscape";
import * as edgehandles from "cytoscape-edgehandles";
import CytoscapeComponent from "react-cytoscapejs";

const EditWorkflow = (props) => {
  const { inputworkflows, inputtype, inputname } = props;

  const [elements, setElements] = useState([]);
  const [loadedWorkflows] = useState(inputworkflows);

  // Setting cy config
  const [cystyle] = useState([
    {
      selector: "node",
      css: {
        label: "data(label)",
        "text-halign": "right",
        "text-valign": "center",
        "font-family":
          "Segoe UI, Tahoma, Geneva, Verdana, sans-serif, sans-serif",
        "font-weight": "lighter",
        "font-size": "15px",
        width: "60px",
        height: "60px",
        padding: "10px",
        margin: "5px",
        "border-width": "2px",
        "background-image":
          'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAAB3RJTUUH4wYMAx0qvwOSBwAACMJJREFUeNrt3GlwE9cBwPH39tDtlawD6hMcDJTYgIQdfMJw2PSAtBnq1tMZpgHbHTIcSQOEgBMTB2iBhsuZFBgKJQ2EK+B0mpqjNNOGpikmEEinBF9EYMuyZEnW4UO29nj9oERRjNvyhDEt8/7fvNp9u/vz6q2kGQkihADp3qIe9gH8P0WwMCJYGBEsjAgWRgQLI4KFEcHCiGBhRLAwIlgYESyMCBZGBAsjgoURwcKIYGFEsDAiWBgRLIwIFkYECyOChRHBwohgYUSwMCJYGBEsjAgWRgQLI4KFEcHCiGBhRLAwIlgYESyMCBZGBAsjgoURM5I78/v9hw696XR2FhYWzJ//3fsf8MzZsxc/+KvJZCwvL9PpdA/8BNAIZrPZppqzGJl63brKYRmwqmoDw6rMliybzTYCxz/ST0OKYmQsS9HDs18IIcsyNPVvR/N6vXfu3OF5fngOfmSMHkoIofb29qbGxu7u7mEZMPY5a2BgoLW11ev1chyXnJys0WgGBga6uroghHq9HgDQZ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x8fHx0eWhN/3hJPJZDKZ7D+MEEGP3uRBMIV7lD91GPaGGUsQeEEUwSP6KyTD+bFyYmLij0tLFAqFwWh82Of1QIpxgh8yhFD4Nk9R1P3fev4HG06sRz4ywWNEsDAiWBgRLIwIFkYECyOChRHBwohgYUSwMCJYGBEsjAgWRgQLI4KFEcHCiGBhRLAwIlgYESyMCBZGBAsjgoURwcKIYGFEsDAiWBgRLIwIFkYECyOChRHBwohgYUSwMCJYGBEsjAgWRgQLo38B7mF1GEUTwy4AAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDYtMTJUMDM6Mjk6NDYtMDQ6MDDu2klzAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA2LTEyVDAzOjI5OjQyLTA0OjAwa8jV3AAAAABJRU5ErkJggg==")',
      },
    },
    {
      selector: `node[type="ACTION"]`,
      css: {
        shape: "square",
        "border-color": "#81c784",
      },
    },
    {
      selector: `node[type="CONDITION"]`,
      css: {
        shape: "diamond",
        "border-color": "##FFEB3B",
        padding: "30px",
      },
    },
    {
      selector: 'node[type="eventAction"]',
      css: {
        "background-color": "#edbd21",
      },
    },
    {
      selector: 'node[type="webhook"]',
      css: {
        "border-color": "#81c784",
        "background-color": "white",
        "background-image":
          'url("data:image/png;base64, ")',
      },
    },
    {
      selector: 'node[type="mq"]',
      css: {
        "background-color": "#edbd21",
      },
    },
    {
      selector: "node[?isStartNode]",
      css: {
        shape: "ellipse",
        "border-width": "2px",
        "border-color": "#80deea",
      },
    },
    {
      selector: "node[?hasErrors]",
      css: {
        color: "#991818",
        "font-style": "italic",
      },
    },
    {
      selector: "node:selected",
      css: {
        "background-color": "#77b0d0",
      },
    },
    {
      selector: ".success-highlight",
      css: {
        "background-color": "#399645",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: ".failure-highlight",
      css: {
        "background-color": "#8e3530",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: ".executing-highlight",
      css: {
        "background-color": "#ffef47",
        "transition-property": "background-color",
        "transition-duration": "0.25s",
      },
    },
    {
      selector: ".awaiting-data-highlight",
      css: {
        "background-color": "#f4ad42",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: "$node > node",
      css: {
        "padding-top": "10px",
        "padding-left": "10px",
        "padding-bottom": "10px",
        "padding-right": "10px",
        "text-valign": "top",
        "text-halign": "center",
      },
    },
    {
      selector: "edge",
      css: {
        "target-arrow-shape": "triangle",
        "curve-style": "bezier",
      },
    },
    {
      selector: "edge.executing-highlight",
      css: {
        width: "5px",
        "target-arrow-color": "#ffef47",
        "line-color": "#ffef47",
        "transition-property": "line-color, width",
        "transition-duration": "0.25s",
      },
    },
    {
      selector: "edge.success-highlight",
      css: {
        width: "5px",
        "target-arrow-color": "#399645",
        "line-color": "#399645",
        "transition-property": "line-color, width",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: "edge[?hasErrors]",
      css: {
        "target-arrow-color": "#991818",
        "line-color": "#991818",
        "line-style": "dashed",
      },
    },
    {
      selector: ".eh-handle",
      style: {
        "background-color": "#337ab7",
        width: "1px",
        height: "1px",
        shape: "triangle",
      },
    },
    {
      selector: ".eh-source",
      style: {
        "border-width": "3",
        "border-color": "#337ab7",
      },
    },
    {
      selector: ".eh-target",
      style: {
        "border-width": "3",
        "border-color": "#337ab7",
      },
    },
    {
      selector: ".eh-preview, .eh-ghost-edge",
      style: {
        "background-color": "#337ab7",
        "line-color": "#337ab7",
        "target-arrow-color": "#337ab7",
        "source-arrow-color": "#337ab7",
      },
    },
  ]);

  useEffect(() => {
    if (elements.length === 0) {
      setupGraph();
    }

    const cyDummy = cytoscape();
    if (!cyDummy.edgehandles) {
      cytoscape.use(edgehandles);
    }
  });

  const setupGraph = () => {
    // Convert our selection arrays to a string
    //if (!this.loadedWorkflow.actions) { this.loadedWorkflow.actions = []; }

    //setTimeout(() => {
    //	if (this.consoleArea && this.consoleArea.codeMirror) this.consoleArea.codeMirror.refresh();
    //});

    // Create the Cytoscape graph
    // http://js.cytoscape.org/#style/labels

    // Breaks stuff
    //container: document.getElementById('cy'),

    // FIXME - needs refresh
    const tmpEdges = loadedWorkflows.map((workflow, count) => {
      return workflow.branches.map((branch) => {
        const edge = {};
        edge.data = {
          id: branch.id,
          _id: branch.id,
          source: branch.source_id,
          target: branch.destination_id,
          hasErrors: branch.has_errors,
        };
        return edge;
      });
    });

    // Make the actual actions
    var edges = [];
    for (var key in tmpEdges) {
      for (var subkey in tmpEdges[key]) {
        edges.push(tmpEdges[key][subkey]);
      }
    }

    const tmpActions = loadedWorkflows.map((workflow, count) => {
      return workflow.actions.map((action) => {
        const node = {
          position: { x: action.position.x, y: action.position.y },
        };
        node.data = {
          id: action["id_"],
          _id: action["id_"],
          label: action.name,
          isStartNode: action["id_"] === loadedWorkflows[count].start,
          hasErrors: action.has_errors,
          type: "ACTION",
        };
        return node;
      });
    });

    // Make the actual actions
    var actions = [];
    for (key in tmpActions) {
      for (subkey in tmpActions[key]) {
        actions.push(tmpActions[key][subkey]);
      }
    }

    const tmpConditionals = loadedWorkflows.map((workflow, count) => {
      return workflow.conditions.map((condition) => {
        const node = {
          position: { x: condition.position.x, y: condition.position.y },
        };
        node.data = {
          id: condition.id_,
          _id: condition.id_,
          label: condition.name,
          isStartNode: condition["id_"] === loadedWorkflows[count].start,
          hasErrors: condition.has_errors,
          type: "CONDITION",
        };
        return node;
      });
    });

    // Make the actual actions
    var conditionals = [];
    for (key in tmpConditionals) {
      for (subkey in tmpConditionals[key]) {
        conditionals.push(tmpConditionals[key][subkey]);
      }
    }

    const tmpelements = [].concat(edges, actions, conditionals);

    if (inputtype !== undefined && inputname !== undefined) {
      // Find startnode, find the movement location and push elements down:
      // FIXME - generate stuff
      const locationvar = 200;
      const baseylocation = 100;
      const hookid = "GENERATEME";
      const hookname = inputname;
      for (key in tmpelements) {
        var item = tmpelements[key];

        if (item.data.isStartNode) {
          // Append a webhook item to the view
          var shiftlength = 0;
          if (item.position.y - locationvar < baseylocation) {
            shiftlength = item.position.y - locationvar + -baseylocation;
            if (shiftlength < 0) {
              shiftlength = -shiftlength;
            }
          }

          const tmpdata = {
            data: { id: hookid, label: hookname, type: inputtype },
            position: { x: item.position.x, y: item.position.y - locationvar },
          };
          const newedge = { data: { source: hookid, target: item.data.id } };
          tmpelements.push(tmpdata);
          tmpelements.push(newedge);

          if (shiftlength !== 0) {
            const newelements = [];
            for (key in tmpelements) {
              // isNaN?
              if (
                tmpelements[key].position === undefined ||
                tmpelements[key].position.isNaN
              ) {
                newelements.push(tmpelements);
                continue;
              }

              var newitem = tmpelements[key];
              newitem.position.y = newitem.position.y + shiftlength;
            }
          }

          break;
        }
      }
    }

    setElements(tmpelements);
  };

  // Set some extra stuff?
  var cy;
  const cytmp = cytoscape();
  cytmp.fit(null, 50);

  return (
    <div>
      <CytoscapeComponent
        cy={(cytmp) => (cy = cytmp)}
        elements={elements}
        style={{ width: "1000px", height: "1000px" }}
        stylesheet={cystyle}
        boxSelectionEnabled={false}
        autounselectify={false}
        wheelSensitivity={0.1}
      />
      ;
    </div>
  );
};

export default EditWorkflow;
