<script>
    import { Row, Col, Button, Icon } from "sveltestrap";

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

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

    export let field;
    export let list = [];
    export let value = [];
    export let id = 0;
    export let error;
    export let onRemoveItem = false;
    export let onSaveItem = false;

    let code = "";
    let codeSpace = "";

    $: isReady = $storeMdjs;
    $: code = getValue(value, "referenceSystemCode");
    $: codeSpace = getValue(value, "referenceSystemCodeSpace");

    function getValue(md, fieldName) {
        return converter.getValue(md, fieldName)[0] || "";
    }

    const converter = new XmlConverter();

    function onSave(fieldName, fieldValue, id) {
        value = converter.setValue(value, fieldName, [fieldValue]);
        onSaveItem(id, value);
    }

    function onRemove(e) {
        e.preventDefault();
        e.stopPropagation();
        if (onRemoveItem) {
            onRemoveItem(id);
        }
    }
</script>

{#if isReady}
    <Row>
        <Col md="11">
            <InputField
                label=""
                type={field.code.type}
                value={code}
                help={field.code.help}
                {error}
                field={field.code.name}
                {id}
                {list}
                {onSave}
            />
        </Col>
        <Col md="3" class="d-none">
            <InputField
                label={field.codeSpace.label}
                type={field.codeSpace.type}
                value={codeSpace}
                help={field.codeSpace.help}
                field={field.codeSpace.name}
                {id}
                {onSave}
            />
        </Col>
        <Col md="1" class="">
            <Button color="dark" outline class="mx-auto py-1 px-2" on:click={onRemove}>
                <Icon name="dash" />
            </Button>
        </Col>
    </Row>
{/if}
