export default {
    props: {
        fieldValue: { type: [String, Number], required: false },
        fieldDataType: { type: String, required: false, default: 'text' }, //'text', 'number', Future to handle: email, domain, password, url
        id: { type: String, required: false },
        disabled: { type: Boolean, required: false, default: false },
        maxLength: { type: Number, required: false, default: -1 },
        placeHolderText: { type: String, required: false, default: '' },
        tooltip: { type: String, required: false, default: '' }
    },
    data() {
        return {
            controlId: this.id ?? 'txt_ins_' + Math.ceil(1000 * 10000 * Math.random() * Math.random()).toString()
        };
    },
    methods: {

        blurHandler: function (e) {
            if (e && e.target && (!e.target.value || e.target.value == ''))
                $(e.target).parent().removeClass('focused');            
        },
        focus: function (e) {
            $(e.target).parent().addClass('focused');
        },
        keyupHandler: function (e) {

            if (e && e.target && e.target.value)
                e.target.value = e.target.value.replace(/[\<\>]+/g, '');

            if (this.fieldDataType && this.fieldDataType != '' && this.fieldDataType.toLowerCase() == 'number' && e && e.target && e.target.value)
                e.target.value = e.target.value.replace(/[^0-9]/g, '');

        }
    },
    mounted: function () {
        // If a tooltip text is provided and Bootstrap tooltip plugin exists, initialize it.
        if (this.tooltip) {
            $('#' + this.controlId).tooltip();
        }
    },
    beforeDestroy: function () {
        // Dispose bootstrap tooltip if initialized
        if (this.tooltip) {
            try { $('#' + this.controlId).tooltip('dispose'); } catch (e) { /* ignore */ }
        }
    },
    template: `

        <div class="form-group">
            <div class="form-line" :class="{focused: fieldValue && fieldValue != ''}">
                <input :id="controlId" type="text" :value="fieldValue" class="form-control" @focus='focus' @blur='blurHandler' @keyup='keyupHandler'
                    @input="$emit('update:fieldValue', $event.target.value)" :disabled="disabled" :maxlength="maxLength > 0 ? maxLength : null"
                    :placeholder="placeHolderText" :title="tooltip" v-bind:data-toggle="tooltip ? 'tooltip' : null" />
            </div>
        </div>

`
}
