<template>
  <span>
    <template v-if="!isValid">{{t('ui.na')}}</template>
    <a v-if="isValid" :href="getHref()">{{getValueDisplay()}}</a> <small v-if="isValid && extension !== null" class="text-muted">{{t('ui.ext')}} {{extension}}</small>
  </span>
</template>

<script>
import { Utils } from './lib/utils.js'
import { useI18n } from 'vue-i18n'

export default {
  props: {
    value: {
      type: String,
      required: false,
      default: null
    },
    extension: {
      type: String,
      required: false,
      default: null
    }
  },
  setup: function(props){
    const { t } = useI18n()
    const match = (props.value ? props.value : '').match( /\+?\d+/g )
    const phoneNumber = match != null ? match.join('') : ''
    const isValid = phoneNumber != '' && !isNaN(phoneNumber.replace('+', ''))

    return { t, isValid, phoneNumber }
  },
  methods: {
    getValueDisplay: function () {
      return this.isValid ? Utils.formatPhone(this.phoneNumber) : this.t('ui.na')
    },
    getHref: function(){
      // @todo: PBX integration( ie:asterisk )
      return this.isValid ? 'tel:'+this.phoneNumber : '#'
    }
  }
}
</script>
