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

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

    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 DataDistributionFormat from "./DataDistributionFormat.svelte";

    export let field;

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

    const converter = new XmlConverter();

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

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

    // TODO: etudier possibilité d'utiliser une function générique dans helpers
    function isDistributionFormat(distributionFormat) {
        return (
            isDefined(converter.getValue(distributionFormat, "formatName")) ||
            isDefined(converter.getValue(distributionFormat, "formatVersion")) ||
            isDefined(converter.getValue(distributionFormat, "formatSpecification"))
        );
    }

    function getValues(mdjs) {
        var distributionFormats = converter.getValue(mdjs, field.name) || [{}];
        var result = [];
        // Clean distributionFormats
        for (var i = 0, n = distributionFormats.length; i < n; i++) {
            if (isDistributionFormat(distributionFormats[i])) {
                result.push(distributionFormats[i]);
            }
        }
        result.push({});
        return result;
    }
    $: values = getValues($storeMdjs);

    onMount(() => {
        helpers.getFile("config/views/formData/formats.json").then((response) => {
            formats = response.data;
        });
    });

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

    function onSaveItem(id, value) {
        values[id] = value;
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
    }
</script>

<Row>
    <Col>
        <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>
    <Col md="4">
        {field.children.formatName.label}
    </Col>
    <Col md="3">
        {field.children.formatVersion.label}
    </Col>
    <Col md="4">
        {field.children.formatSpecification.label}
    </Col>
    <Col md="1" />
</Row> -->

<Row class="my-2">
    <Col>
        {#each values as value, id}
            <DataDistributionFormat field={field.children} {value} {id} {onRemoveItem} {onSaveItem} {error} {formats} />
        {/each}
    </Col>
</Row>

<Row class="justify-content-md-end">
    <Col>
        {#if $validateForm && error.required && field.error.message}
            <small class="text-danger">{field.error.message}</small>
        {/if}
    </Col>
</Row>
