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

    import { Row, Col, 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 DataIdentifier from "./DataIdentifier.svelte";

    export let field;

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

    const converter = new XmlConverter();

    $: isReady = $storeMdjs;

    function getValues(mdjs) {
        var identifiers = mdjs ? converter.getValue(mdjs, field.name) : [{}];
        for (let i = 0; i < identifiers.length; i++) {
            if (converter.getValue(identifiers[i], "mdCode").length) {
                var mdCode = converter.getValue(identifiers[i], "mdCode");
                identifiers[i] = converter.setValue({}, "code", mdCode);
            }
        }
        identifiers = helpers.cleanValues(identifiers, "code", true);
        return identifiers;
    }

    $: values = getValues($storeMdjs);

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

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

    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, value) {
        var identifiers = lodash.cloneDeep(values);
        identifiers[id] = value;
        for (var i = 0; i < identifiers.length; i++) {
            var codeSpace = converter.getValue(identifiers[i], "codeSpace");
            if (!codeSpace.length || !codeSpace[0]) {
                var code = converter.getValue(identifiers[i], "code");
                identifiers[i] = converter.setValue({}, "mdCode", code);
            }
        }
        $storeMdjs = converter.setValue($storeMdjs, field.name, identifiers);
    }
</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}
            <DataIdentifier field={field.children} identifier={value} {id} {onRemoveItem} {onSaveItem} {error} />
        {/each}
        <Row class="justify-content-md-end">
            <Col class="">
                {#if $validateForm && error.required && field.error.message}
                    <small class="text-danger">{field.error.message}</small>
                {/if}
            </Col>
        </Row>
    </Col>
</Row>
