<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 identifier = {};
    export let id = 0;
    export let error;
    export let onRemoveItem = false;
    export let onSaveItem = false;

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

    $: isReady = $storeMdjs;
    $: code = getValue(identifier, "code");
    $: codeSpace = getValue(identifier, "codeSpace");

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

    const converter = new XmlConverter();

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

    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}
                field={field.code.name}
                {id}
                {error}
                {onSave}
            />
        </Col>
        <Col md="3" class="d-none">
            <InputField
                label={field.codeSpace.label}
                type={field.codeSpace.type}
                value={codeSpace}
                help={field.codeSpace.help}
                error={field.codeSpace.error}
                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}
