<script>
    import { onMount } from "svelte";
    import { storeMdjs } from "@/stores/mdjs.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";
    import helpers from "@/libs/helpers";

    import MultiInputField from "./elements/MultiInputField.svelte";

    export let field;

    let values = [""];

    $: isReady = $storeMdjs;

    const converter = new XmlConverter();

    function getValues(mdjs) {
        var resourceConstraints = converter.getValue(mdjs, "dataResourceConstraints");
        var result = [];
        for (var i = 0; i < resourceConstraints.length; i++) {
            var useLimitations = converter.getValue(resourceConstraints[i], "dataUseLimitations");
            if (useLimitations.length) {
                result = result.concat(useLimitations);
            }
        }
        return result || [""];
    }

    $: {
        values = getValues($storeMdjs);
        values = helpers.cleanValues(values, false, true);
    }

    onMount(() => {});

    function onRemove(id) {
        if (values.length > 1) {
            values.splice(id, 1);
        } else {
            values[id] = "";
        }
        updateUseLimitations(field.name, values);
    }

    function onSave(fieldName, fieldValue, id) {
        values[id] = fieldValue;
        updateUseLimitations(fieldName, values);
    }

    function updateUseLimitations(fieldName, fieldValues) {
        var useLimitations = converter.setValue({}, fieldName, fieldValues);
        // Get all resourceConstraints except constraints
        var resourceConstraints = converter.getValue($storeMdjs, "dataResourceConstraints");
        var constraints = [];
        for (var i = 0; i < resourceConstraints.length; i++) {
            if (!converter.getValue(resourceConstraints[i], "dataUseLimitations").length) {
                constraints.push(resourceConstraints[i]);
            }
        }
        constraints = constraints.concat(useLimitations);
        $storeMdjs = converter.setValue($storeMdjs, "dataResourceConstraints", constraints);
    }
</script>

{#if isReady}
    <MultiInputField {field} {values} {onSave} {onRemove} rows={2} strong={true} />
{/if}

<style>
</style>
