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

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

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

    import DataBrowseGraphic from "./DataBrowseGraphic.svelte";

    export let field;

    let values = [];
    let displayHelp = false;

    $: isReady = $storeMdjs;

    const converter = new XmlConverter();

    function getValues(mdjs) {
        return converter.getValue(mdjs, field.name) || [{}];
    }

    $: values = getValues($storeMdjs);

    onMount(() => {});

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

    // TODO: conserver la possibilité d'ajouter plusieurs illustrations
    function onRemoveItem(id) {
        if (values.length > 1) {
            values.splice(id, 1);
        } else {
            values[id] = {};
        }
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
    }

    // TODO: conserver la possibilité d'ajouter plusieurs illustrations
    function onSaveItem(id, value) {
        values[id] = value;
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
    }
</script>

<Row>
    <Col md="12" class="mb-3">
        <strong>{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 class="my-1">
    <Col>
        {#each values as value, id}
            <DataBrowseGraphic field={field.children} {value} {id} {onSaveItem} />
        {/each}
    </Col>
</Row>
