'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var util = require('../../../../../../zrender@6.0.0/node_modules/zrender/lib/core/util.js');
var SeriesData = require('../../data/SeriesData.js');
var Graph = require('../../data/Graph.js');
var linkSeriesData = require('../../data/helper/linkSeriesData.js');
var createDimensions = require('../../data/helper/createDimensions.js');
var CoordinateSystem = require('../../core/CoordinateSystem.js');
var createSeriesData = require('./createSeriesData.js');
var model = require('../../util/model.js');

function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  // ??? TODO
  // support dataset?
  var graph = new Graph.default(directed);
  for (var i = 0; i < nodes.length; i++) {
    graph.addNode(util.retrieve(
    // Id, name, dataIndex
    nodes[i].id, nodes[i].name, i), i);
  }
  var linkNameList = [];
  var validEdges = [];
  var linkCount = 0;
  for (var i = 0; i < edges.length; i++) {
    var link = edges[i];
    var source = link.source;
    var target = link.target;
    // addEdge may fail when source or target not exists
    if (graph.addEdge(source, target, linkCount)) {
      validEdges.push(link);
      linkNameList.push(util.retrieve(model.convertOptionIdName(link.id, null), source + ' > ' + target));
      linkCount++;
    }
  }
  var coordSys = seriesModel.get('coordinateSystem');
  var nodeData;
  if (coordSys === 'cartesian2d' || coordSys === 'polar' || coordSys === 'matrix') {
    nodeData = createSeriesData.default(nodes, seriesModel);
  } else {
    var coordSysCtor = CoordinateSystem.default.get(coordSys);
    var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : [];
    // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
    // `value` dimension, but graph need `value` dimension. It's better to
    // uniform this behavior.
    if (util.indexOf(coordDimensions, 'value') < 0) {
      coordDimensions.concat(['value']);
    }
    var dimensions = createDimensions.default(nodes, {
      coordDimensions: coordDimensions,
      encodeDefine: seriesModel.getEncode()
    }).dimensions;
    nodeData = new SeriesData.default(dimensions, seriesModel);
    nodeData.initData(nodes);
  }
  var edgeData = new SeriesData.default(['value'], seriesModel);
  edgeData.initData(validEdges, linkNameList);
  beforeLink && beforeLink(nodeData, edgeData);
  linkSeriesData.default({
    mainData: nodeData,
    struct: graph,
    structAttr: 'graph',
    datas: {
      node: nodeData,
      edge: edgeData
    },
    datasAttr: {
      node: 'data',
      edge: 'edgeData'
    }
  });
  // Update dataIndex of nodes and edges because invalid edge may be removed
  graph.update();
  return graph;
}

exports.default = createGraphFromNodeEdge;
