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

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

    import DragDrop from "@/components/DragDrop.svelte";
    import { storeMdjs } from "@/stores/mdjs.store";
    import { storeFiles, storeUrlFiles, storeDeletedFiles, storeNewFiles } from "@/stores/files.store";
    import { storeConfig } from "@/stores/config.store";
    import { user } from "@/stores/app.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";
    import helpers from "@/libs/helpers";

    import DataLinkage from "./DataLinkage.svelte";

    export let field;
    export let listProtocols = [];

    let displayHelp = false;
    let values = [];
    let errors = [];

    $: isReady = $storeMdjs;

    const converter = new XmlConverter();

    // 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 isLinkage(linkage) {
        return isDefined(converter.getValue(linkage, "linkageUrl"));
    }

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

    onMount(() => {});

    function OnDrop(files) {
        for (let i = 0, n = files.length; i < n; i++) {
            if (files[i]) {
                const id = values.length;
                $storeNewFiles["linkage-" + id] = files[i];
                // console.log(888, id, i, files, files[i]);
                errors[id - 1] = files[i].size > $storeConfig.api.fileMaxSize ? true : false;
                let link = converter.setValue({}, "linkageUrl", ["file:///" + files[i].name]);
                link = converter.setValue(link, "linkageName", [files[i].name]);
                onSaveItem(id, link);
            }
        }
    }

    function onRemoveItem(id) {
        if (values.length > 1) {
            values.splice(id, 1);
            errors.splice([id], 1);
            errors = errors;
        } 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 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 class="my-2">
    <Col>
        {#if $user.editor}
            <DragDrop
                {OnDrop}
                autoUpload={false}
                multiple={true}
                accept="*"
                text="Déposez un ou plusieurs fichiers par glisser/déposer - Taille maximale: 50 Mo"
            />
        {/if}
    </Col>
</Row>

<hr />

<Row class="my-1">
    <Col>
        {#each values as value, id}
            <DataLinkage
                field={field.children}
                {value}
                {id}
                {onRemoveItem}
                {onSaveItem}
                {listProtocols}
                error={errors[id]}
            />
            <hr />
        {/each}
    </Col>
</Row>
