"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.appStateToSavedWorkspace = appStateToSavedWorkspace;
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function serializeNode({
  data,
  scaledSize,
  parent,
  x,
  y,
  label,
  color
}, allNodes = []) {
  return {
    x,
    y,
    label,
    color,
    field: data.field,
    term: data.term,
    parent: parent ? allNodes.indexOf(parent) : null,
    size: scaledSize
  };
}
function serializeEdge({
  source,
  target,
  weight,
  width,
  label
}, allNodes = []) {
  return {
    weight,
    width,
    label,
    source: allNodes.indexOf(source),
    target: allNodes.indexOf(target)
  };
}
function serializeUrlTemplate({
  encoder,
  icon,
  url,
  description,
  isDefault
}) {
  const serializedTemplate = {
    url,
    description,
    isDefault,
    encoderID: encoder.id
  };
  if (icon) {
    serializedTemplate.iconClass = icon.id;
  }
  return serializedTemplate;
}
function serializeField({
  name,
  icon,
  hopSize,
  lastValidHopSize,
  color,
  selected
}) {
  return {
    name,
    hopSize,
    lastValidHopSize,
    color,
    selected,
    iconClass: icon.id
  };
}
function appStateToSavedWorkspace(currentSavedWorkspace, {
  workspace,
  urlTemplates,
  advancedSettings,
  selectedIndex,
  selectedFields
}, canSaveData) {
  const blocklist = canSaveData ? workspace.blocklistedNodes.map(node => serializeNode(node)) : [];
  const vertices = canSaveData ? workspace.nodes.map(node => serializeNode(node, workspace.nodes)) : [];
  const links = canSaveData ? workspace.edges.map(edge => serializeEdge(edge, workspace.nodes)) : [];
  const mappedUrlTemplates = urlTemplates.map(serializeUrlTemplate);
  const persistedWorkspaceState = {
    indexPattern: selectedIndex.id,
    selectedFields: selectedFields.map(serializeField),
    blocklist,
    vertices,
    links,
    urlTemplates: mappedUrlTemplates,
    exploreControls: advancedSettings
  };
  currentSavedWorkspace.wsState = JSON.stringify(persistedWorkspaceState);
  currentSavedWorkspace.numVertices = vertices.length;
  currentSavedWorkspace.numLinks = links.length;
}