import { StedGraph, StedNode } from './sted-graph/sted-graph-type'

type Equipment = {
  type: string
  refid: string
  [key: string]: any
}

function transform(graphicNodes: any[], equipment: Equipment): StedNode {
  const { type, refid } = equipment

  const links = graphicNodes.filter(node => {
    const { from, to } = node
    return from && to && from.component && to.component && (from.component === refid || to.component === refid)
  })

  const outlets = links
    .filter(link => link.from.component === refid)
    .map(link => {
      const {
        refid,
        streamType = 'fluid',
        loopInitializationPoint = false,
        initY = {},
        initm = 0,
        initp = 0,
        initT = 0
      } = link
      const { component, anchor } = link.to
      const initData = loopInitializationPoint
        ? {
            initY,
            initm,
            initT,
            initp
          }
        : {}

      return {
        name: refid,
        type: streamType,
        kind: link.from.anchor,
        dstNode: component,
        dstEdge: anchor,
        loopInitializationPoint,
        initData
      }
    })
  const inlets = links
    .filter(link => link.to.component === refid)
    .map(link => {
      const {
        refid,
        streamType = 'fluid',
        loopInitializationPoint = false,
        initY = {},
        initm = 0,
        initp = 0,
        initT = 0
      } = link
      const { component, anchor } = link.from
      const initData = loopInitializationPoint
        ? {
            initY,
            initm,
            initT,
            initp
          }
        : {}

      return {
        name: refid,
        type: streamType,
        kind: link.to.anchor,
        srcNode: component,
        srcEdge: anchor,
        loopInitializationPoint,
        initData
      }
    })

  return {
    type,
    name: String(refid),
    params: {
      ...equipment
    },
    inlets,
    outlets
  }
}

export function transformGraphicModelToStedModel(graphicModel: any): StedGraph {
  var graphicNodes: any[] = graphicModel.components || []

  return {
    stedNodes: graphicNodes.filter(node => node.equipment).map(node => transform(graphicNodes, node))
  }
}
