<script setup>
import { nextTick, ref, watch } from 'vue';
import { QInput } from 'quasar';

const $props = defineProps({
    modelValue: {
        type: String,
        default: '',
    },
    insertable: {
        type: Boolean,
        default: false,
    },
});

const emit = defineEmits(['update:modelValue', 'accountShortToStandard']);

let internalValue = ref($props.modelValue);

watch(
    () => $props.modelValue,
    (newVal) => {
        internalValue.value = newVal;
    }
);

watch(
    () => internalValue.value,
    (newVal) => {
        emit('update:modelValue', newVal);
        accountShortToStandard();
    }
);

const handleKeydown = (e) => {
    if (e.key === 'Backspace') return;
    if (e.key === '.') {
        accountShortToStandard();
        // TODO: Fix this setTimeout, with nextTick doesn't work
        setTimeout(() => {
            setCursorPosition(0, e.target);
        }, 1);
        return;
    }

    if ($props.insertable && e.key.match(/[0-9]/)) {
        handleInsertMode(e);
    }
};
function setCursorPosition(pos, el = vnInputRef.value) {
    el.focus();
    el.setSelectionRange(pos, pos);
}
const vnInputRef = ref(false);
const handleInsertMode = (e) => {
    e.preventDefault();
    const input = e.target;
    const cursorPos = input.selectionStart;
    const { maxlength } = vnInputRef.value;
    let currentValue = internalValue.value;
    if (!currentValue) currentValue = e.key;
    const newValue = e.key;
    if (newValue && !isNaN(newValue) && cursorPos < maxlength) {
        internalValue.value =
            currentValue.substring(0, cursorPos) +
            newValue +
            currentValue.substring(cursorPos + 1);
    }
    nextTick(() => {
        input.setSelectionRange(cursorPos + 1, cursorPos + 1);
    });
};
function accountShortToStandard() {
    internalValue.value = internalValue.value?.replace(
        '.',
        '0'.repeat(11 - internalValue.value.length)
    );
}
</script>

<template>
    <QInput @keydown="handleKeydown" ref="vnInputRef" v-model="internalValue" />
</template>
