<template>
    <input :class="cx('root')" :value="d_displayValue" :aria-invalid="invalid || undefined" @input="onInput"  @change="onChange"  @focus="onFocus" v-bind="getPTOptions('root')" />
</template>

<script>
import BaseInputText from './BaseInputText.vue';

export default {
    name: 'InputText',
    extends: BaseInputText,
    inheritAttrs: false,
    emits: ['update:modelValue','update-editing-cell-class'],
    data(){
       return{
           d_displayValue: this.modelValue
       }
    },
    watch: {
        modelValue(newValue) {
          if(newValue!==this.d_displayValue){
              this.d_displayValue = this.formatValue( newValue);
          }
        },
    },
    created(){
       if(this.tableCellEditor){
            this.$emit("update-editing-cell-class");
       }
    },
    methods: {
        getPTOptions(key) {
            const _ptm = key === 'root' ? this.ptmi : this.ptm;

            return _ptm(key, {
                context: {
                    filled: this.filled,
                    disabled: this.$attrs.disabled || this.$attrs.disabled === ''
                }
            });
        },
        onInput(event) {
            //this.$emit('update:modelValue', event.target.value);
            this.d_displayValue  = this.formatValue( event.target.value || '');
        },
        onChange(event) {
            const value= this.formatValue( event.target.value || '');

            if(value!==this.d_displayValue){
                this.d_displayValue = value;
            }
            
            this.$emit('update:modelValue', value);
        },

        onFocus(){
            this.autoSelection && this.$el.select();
        },
         formatValue(value){

            if( value===null || value===undefined || value==='' )
                return '';

            let case2=this.case.trim().toUpperCase();
            if(case2 ==='UPPER'){
                value =value.toString().toUpperCase();
            }
            else if(case2 ==='LOWER'){
                value = value.toString().toLowerCase();
            }
           return value;
         },
    },
    computed: {
        filled() {
            return this.modelValue != null && this.modelValue.toString().length > 0;
        }
    }
};
</script>
