<script>
    import {createEventDispatcher, getContext} from "svelte";
    import {previewTitle} from "../../records/Preview";

    const channel = getContext("channel");
    const dispatch = createEventDispatcher();
    export let schema;
    export let operators;
    export let key;
    export let value;
    export let inModal;
    export let modalUrl;
    export let graph;

    let filter = {
        label: "",
        operator: "",
        value: value,
        isReference: key.startsWith("children"),
    };

    filter = [
        extractOperator(key),
        extractLabel(schema, key),
    ].reduce((mem, fn) => fn(mem), filter);

    function extractOperator(key) {
        return (filter) => {
            if (filter.isReference) {
                filter.operator = "eq";
                return filter;
            }
            const filterSplit = key.split("_");
            filter.operator = filterSplit[filterSplit.length - 1] ?? "eq";
            return filter;
        };
    }

    function extractLabel(schema, key) {
        return (filter) => {
            let fieldName = "";
            if (filter.isReference) {
                fieldName = key.split(".")[1];
            } else {
                fieldName = key.replace("_" + filter.operator, "");
            }
            const filterField = schema.fields.find((f) => f.name === fieldName);
            filter.label = filterField?.label ?? fieldName;
            return filter;
        }

    }

    const filterRecord = extractFilterRecord(graph, value);

    function extractFilterRecord(graph, value) {
        if (!filter.isReference) {
            return null;
        }
        return graph.records.find(r => r.id === value);
    }

    function removeFilter(k) {
        let filterKey = `filter[${k}]`;
        const url = new URL(modalUrl ?? window.location.href);
        url.searchParams.set("skip", "0");
        url.searchParams.delete(filterKey);
        if (inModal) {
            dispatch("refresh", url);
        } else {
            window.location.replace(url);
        }
    }
</script>

<span class="applied-filter d-inline-block border border-primary rounded lx-small-text  me-1 px-2 py-1">
    <div class="d-flex align-items-center justify-content-center">
        {#if filter.isReference && filterRecord}
              {filter.label} is {previewTitle(channel.schemas, filterRecord)}
        {:else}
              {filter.label} {operators.find((o) => o.name === filter.operator)?.symbol ?? ""} {value}
        {/if}
        <button
                on:click|preventDefault={() => removeFilter(key)}
                type="button"
                class="btn-close btn-close ms-1"
                aria-label="Close"
        />
    </div>
</span>

<style>
    .applied-filter {
        background-color: #fff;
        line-height: 22px;
    }

    .applied-filter:hover {
        opacity: .8;
        background-color: #eee;
    }
</style>
