import {uniqBy} from "lodash";
import axios from "axios";

export function insertEdges(graph, sourceRecord, targetRecords, fieldName, action = "") {
    let newEdges = targetRecords.map((r) => {
        return {
            target: r.id,
            source: sourceRecord.id,
            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;
}


export function graphToReferences(graph,record,field){
    return graph.edges
        .filter((edge) => edge.field === field.name)
        .map((edge) => {
            return {
                record: graph.records.find((increc) => increc.id === edge.target && record.id === edge.source),
                edge: edge
            };
        }).filter((rec) => (rec.record?.id ? true : false)) ?? [];
}

export function removeReferenceFromGraph(graph,field,id){
    return graph.edges.map(
        (edge) => {
            if(edge.target === id && edge.field === field.name){
                edge._isTrashed = true;
            }
            return edge;
        }
    );
}

export function restoreReferenceToGraph(graph,field,id){
    return graph.edges.map(
        (edge) => {
            if(edge.target === id && edge.field === field.name){
                edge._isTrashed = false;
            }
            return edge;
        }
    );
}


export function fullDeleteRecord(channel,graph,field,id){
    axios
        .post(channel.lucentUrl + "/records/status/trashed" , {
            records: [id]
        });

    return graph.edges.filter(
        (edge) => !(edge.target === id && edge.field === field.name)
    );
}
