<script>
    import { onMount } from "svelte";

    import { Row, Col, Button, Icon, FormText } from "sveltestrap";

    import lodash from "lodash";

    import { storeMdjs } from "@/stores/mdjs.store";
    import { validateForm } from "@/stores/app.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";
    import helpers from "@/libs/helpers";

    import DataReferenceSystem from "./DataReferenceSystem.svelte";

    export let field;
    export let list = [];

    let values = [];
    let displayHelp = false;
    let error = {
        required: true,
        message: false,
    };

    $: isReady = $storeMdjs;

    const converter = new XmlConverter();

    // TODO:  Put in helpers (use isEmptyArray)
    function isDefined(array) {
        return array.filter((item) => item).length;
    }

    $: {
        const referenceSystems = getValues($storeMdjs);
        let isValid = [];
        let valid = false;
        for (let i = 0, n = referenceSystems.length; i < n; i++) {
            valid = isDefined(converter.getValue(referenceSystems[i], "referenceSystemCode")) ? true : false;
            isValid.push(valid);
        }
        error.required = field.error.required ? isValid.every((value) => value == false) : false;
    }

    function getValues(mdjs) {
        var referenceSystems = mdjs ? converter.getValue(mdjs, field.name) : [{}];
        var result = [];
        for (let r = 0; r < referenceSystems.length; r++) {
            var code = converter.getValue(referenceSystems[r], "referenceSystemCode")[0] || false;
            if (code) {
                var listValue =
                    list.find((v) => {
                        return code.toLowerCase().includes(v.search);
                    }) || code;
                referenceSystems[r] = converter.setValue(referenceSystems[r], "referenceSystemCode", [listValue.value]);
                result.push(referenceSystems[r]);
            }
        }
        return helpers.cleanValues(result, "referenceSystemCode", true);
    }
    $: values = getValues($storeMdjs);

    onMount(() => {});

    function onRemoveItem(id) {
        if (values.length > 1) {
            values.splice(id, 1);
        } else {
            values[id] = {};
        }
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
    }

    function onSaveItem(id, item) {
        item = converter.setValue(item, "referenceSystemCodeSpace", "EPSG");
        values[id] = item;

        var items = [];
        for (var r = 0; r < values.length; r++) {
            var ref = lodash.cloneDeep(values[r]);
            var code = converter.getValue(ref, "referenceSystemCode")[0];
            if (code) {
                for (var l = 0; l < list.length; l++) {
                    if (code.toLowerCase().includes(list[l].search.toLowerCase())) {
                        ref = converter.setValue(ref, "referenceSystemCode", [list[l].value]);
                    }
                }
                items.push(ref);
            }
        }
        $storeMdjs = converter.setValue($storeMdjs, field.name, items);
    }
</script>

<Row>
    <Col>
        <strong>
            {field.label}
            {#if field.error.required}
                <span class="text-danger"> * </span>
            {/if}
        </strong>
        <!-- If help -->
        {#if field.help}
            <span
                class="link"
                on:click={() => {
                    displayHelp = !displayHelp;
                }}
            >
                <Icon name="info-circle-fill" class="ms-1 mb-1" />
            </span>
        {/if}
        <!-- If display help -->
        {#if displayHelp}
            <FormText color="muted" class="d-block">
                {@html helpers.nl2br(field.help)}
            </FormText>
        {/if}
    </Col>
</Row>

<Row class="my-2">
    <Col>
        {#each values as value, id}
            <DataReferenceSystem field={field.children} {value} {id} {list} {onRemoveItem} {onSaveItem} {error} />
        {/each}
    </Col>
</Row>
<Row class="mt-0 justify-content-md-end">
    <Col class="mt-n3">
        {#if $validateForm && error.required && field.error.message}
            <small class="text-danger">{field.error.message}</small>
        {/if}
    </Col>
</Row>
