import {uniqBy} from "lodash";

export function insertEdges(graph, sourceRecord, targetRecords, fieldName, action = "") {
    let newEdges = targetRecords.map((r) => {
        return {
            target: r.id,
            source: sourceRecord.id,
            sourceSchema: sourceRecord.schema,
            targetSchema: r.schema,
            field: fieldName,
            depth: 1,
            rank: ""
        };
    });

    let replacedEdges = graph.edges;
    if (action === "replace") {
        replacedEdges = replacedEdges.filter((edge) => edge.field !== field.name);
    }

    graph.records = uniqBy([...graph.records, ...targetRecords], (r) => r.id);
    graph.edges = uniqBy([...replacedEdges, ...newEdges], (edge) =>  edge.source +  edge.target + edge.field + edge.depth);
    return graph;
}
