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

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

    export let field;

    let value = formatDate();

    $: isReady = $storeMdjs;

    $: value = converter.getValue($storeMdjs, field.name, field.space)[0]
        ? new Date(Date.parse(converter.getValue($storeMdjs, field.name, field.space)[0])).toISOString().slice(0, 10)
        : formatDate();

    const converter = new XmlConverter();

    function formatDate(date) {
        date = date || Date.now();
        var d = new Date(date);
        var month = (d.getMonth() + 1).toString();
        month = month.length < 2 ? "0" + month : month;
        var day = d.getDate().toString();
        day = day.length < 2 ? "0" + day : day;
        var year = d.getFullYear().toString();
        return [year, month, day].join("-");
    }

    function onSave(field, value, space) {
        space = space || "md";
        $storeMdjs = converter.setValue($storeMdjs, field, [value], space);
    }
</script>

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

<style>
</style>
