<script>
    import {getContext} from "svelte";
    import {
        fullDeleteRecord,
        graphToReferences,
        insertEdges,
        removeReferenceFromGraph,
        restoreReferenceToGraph
    } from "./reference";
    import {getErrorMessage} from "./errorMessage";
    import {sortByField} from "../../edges/sortEdges";
    import ReferenceInlineButtons from "./ReferenceInlineButtons.svelte";
    import Sortable from "../../libs/Sortable.svelte";
    import PreviewReference from "../previews/PreviewReference.svelte";

    const channel = getContext("channel");
    export let record;
    export let field;
    export let graph;
    export let validationErrors;
    $: errorMessage = getErrorMessage(validationErrors, field.name);


    $: references = graphToReferences(graph,record,field)

    let collections = channel.schemas.filter((aschema) =>
        field.collections.includes(aschema.name)
    );

    function removeReference(e) {
        e.preventDefault();
        graph.edges = removeReferenceFromGraph(graph,field,e.detail)
    }

    function restoreReference(e) {
        e.preventDefault();
        graph.edges = restoreReferenceToGraph(graph,field,e.detail)
    }

    function fullDelete(e) {
        e.preventDefault();
        graph.edges = fullDeleteRecord(channel,graph, field, e.detail)
    }

    function reorder(e) {
        graph.edges = sortByField(e.detail.source, e.detail.target, graph.edges, field.name, references);
    }

    function insert(e) {
        e.preventDefault();
        graph = insertEdges(graph, record, e.detail.records, field.name, e.detail.action);
    }

</script>

{#if errorMessage}
    <div class="invalid-feedback d-block mb-3">
        {errorMessage}
    </div>
{/if}
<div class="inline-card-wrapper">
    <ReferenceInlineButtons
            recordId={null}
            schemas={collections}
            on:insert={insert}
            on:save={insert}
    />
</div>
{#if references.length > 0}
    <Sortable sortableClass="row row-cols-3 mt-3" on:update={reorder}>
        {#each references as reference (reference.record.id)}
            <div>
                <PreviewReference
                        {graph}
                        record={reference.record}
                        edge={reference.edge}
                        hasDelete={true}
                        on:remove={removeReference}
                        on:restore={restoreReference}
                        on:fulldelete={fullDelete}
                />
            </div>
        {/each}
    </Sortable>
{/if}
