<script>
    import {getContext} from "svelte";
    import {uniqBy} from "lodash";
    import PreviewCard from "../PreviewCard.svelte";
    import {getErrorMessage} from "./errorMessage";
    import {sortByField} from "../../edges/sortEdges";
    import ReferenceInlineButtons from "./ReferenceInlineButtons.svelte";
    import Sortable from "../../libs/Sortable.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);
    }

    function insert(e) {
        e.preventDefault();
        const recordsToInsert = e.detail.records;
        const action = e.detail.action;
        let newEdges = recordsToInsert.map((r) => {
            return {
                target: r.id,
                source: record.id,
                sourceSchema: record.schema,
                targetSchema: r.schema,
                field: field.name,
                rank: ""
            };
        });

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

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

</script>

{#if errorMessage}
    <div class="invalid-feedback d-block mb-3">
        {errorMessage}
    </div>
{/if}
<div class="inline-card-wrapper">
    <ReferenceInlineButtons
        {field}
        buttonClass="mt-2"
        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 class="col mb-3">
                <PreviewCard
                    classes="h-100"
                    record={reference}
                    hasDelete={true}
                    on:remove={removeReference}
                />
            </div>
        {/each}
    </Sortable>
{/if}
