<template>
    <div>
        <input
            v-model="value"
            type="text"
            class="uk-input"
            :class="{ 'uk-form-danger': inUse }"
            @input="set($event.target.value)"
        />
        <span v-if="inUse" class="uk-text-meta">{{
            $t('Name already assigned to another field.')
        }}</span>
    </div>
</template>

<script>
import fields from '@yootheme/fields';

export default {
    extends: fields.components.FieldText,

    inject: {
        $node: {
            default: null,
        },
        Form: {
            from: 'EssentialsForm',
        },
    },

    computed: {
        closestForm() {
            return this.Form.closestForm(this.$node);
        },

        controls() {
            return this.closestForm ? this.Form.controls(this.closestForm) : [];
        },

        inUse() {
            return this.controls.filter((v) => v === this.value).length > 1;
        },
    },

    methods: {
        set(value) {
            // remove unsupported characters and double spaces
            this.value = value.replace(/[^a-zA-Z0-9_ ]|^\s|\s{2,}/, '');

            // trim after last input
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                this.value = this.value.trim();
            }, 1000);
        },
    },
};
</script>
