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

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

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

    import DataTemporalExtent from "./DataTemporalExtent.svelte";

    export let field;

    let values = [];
    let displayHelp = false;

    $: isReady = $storeMdjs;

    const converter = new XmlConverter();

    onMount(() => {
        if (!values || values.length == 0) {
            values = [{}];
        }
    });

    function onAddItem(e) {
        e.preventDefault();
        e.stopPropagation();
        values[values.length] = {};
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
    }

    function onRemoveItem(id) {
        if (values.length > 1) {
            values.splice(id, 1);
        } else {
            values[id] = {};
        }
        values = values;
    }

    function onSaveItem(id, value) {
        values[id] = value;
    }
</script>

<Row>
    <Col>
        <strong class="mb-3">{field.label}</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>
    <Col md="5">
        {field.children.extentName.label}
    </Col>
    <Col md="3">
        {field.children.temporalExtentBegin.label}
    </Col>
    <Col md="3">
        {field.children.temporalExtentEnd.label}
    </Col>
    <Col md="1" />
</Row>

<Row class="my-2">
    <Col>
        {#each values as value, id}
            <DataTemporalExtent field={field.children} {value} {id} {onRemoveItem} {onSaveItem} />
        {/each}
        <Row class="mt-1 justify-content-md-end">
            <Col md="1">
                <Button color="dark" outline class="mx-auto py-1 px-2" on:click={onAddItem}>
                    <Icon name="plus" />
                </Button>
            </Col>
        </Row>
    </Col>
</Row>
