<script>
    import {getContext} from "svelte";
    import {insertEdges} 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 = graph.edges
        .filter((edge) => edge.field === field.name)
        .map((edge) => {
            return graph.records.find((increc) => increc.id === edge.target && record.id === edge.source);
        }).filter((rec) => (rec?.id ? true : false)) ?? [];

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

    function removeReference(e) {
        e.preventDefault();
        graph.edges = graph.edges.filter(
            (edge) => !(edge.target === e.detail && edge.field === field.name)
        );
    }

    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.id)}
            <div>
                <PreviewReference
                    record={reference}
                    hasDelete={true}
                    on:remove={removeReference}
                />
            </div>
        {/each}
    </Sortable>
{/if}
