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

    import InputField from "./elements/InputField.svelte";
    import { onMount } from "svelte";

    export let field;
    export let list;
    export let strong;

    let value = "";

    $: isReady = $storeMdjs;

    $: value = $storeMdjs ? converter.getValue($storeMdjs, field.name)[0] : "";

    const converter = new XmlConverter();

    function getValue() {
        var dataResourceConstraints = converter.getValue($storeMdjs, "dataResourceConstraints");
        for (var i = 0; i < dataResourceConstraints.length; i++) {
            const dataResourceConstraint = converter.getValue(dataResourceConstraints[i], "dataSecurityClassification");
            if (dataResourceConstraint.length) {
                return dataResourceConstraint[0];
            }
        }
        return "";
    }

    onMount(() => {
        value = getValue();
    });

    function onSave(fieldName, fieldValue) {
        var classification = converter.setValue({}, fieldName, [fieldValue]);

        // Get all resourceConstraints except securityConstraints
        var dataResourceConstraints = converter.getValue($storeMdjs, "dataResourceConstraints");
        var resourcesConstraints = [];
        for (var i = 0; i < dataResourceConstraints.length; i++) {
            const dataResourceConstraint = converter.getValue(dataResourceConstraints[i], "dataSecurityClassification");
            if (!dataResourceConstraint.length) {
                resourcesConstraints.push(dataResourceConstraints[i]);
            }
        }
        resourcesConstraints = resourcesConstraints.concat(classification);
        $storeMdjs = converter.setValue($storeMdjs, "dataResourceConstraints", resourcesConstraints);
        value = getValue();
    }
</script>

{#if isReady}
    <InputField
        label={field.label}
        type={field.type}
        {value}
        {list}
        help={field.help}
        error={field.error}
        field={field.name}
        {strong}
        {onSave}
    />
{/if}

<style>
</style>
