import { mapActions, mapGetters } from 'vuex'

export default {
  data() {
    return {
      phoneMixinInitialized: false,
    }
  },
  computed: {
    ...mapGetters(['getAllCountries', 'getCountries', 'getCountriesCallCode']),
    callCodeList() {
      return this.getAllCountries.map(country => {
        return {
          ...country,
          value: country.id,
          text: country.code_iso_2 + ' (+' + country.call_code + ')',
          name: this.$helpers.getValue(country, 'translated_name.content', country.name),
        }
      })
    },
    callCountryList() {
      return this.callCodeList.map(country => {
        return {
          value: country.value,
          text: this.$helpers.getValue(country, 'translated_name.content', country.name),
        }
      })
    },
  },
  async mounted() {
    await this.initPhoneMixin()
  },
  methods: {
    ...mapActions(['loadAllCountries', 'loadCountries']),
    initPhoneMixin: async function() {
      // check phoneMixinInitialized = false to avoid duplicate api calls
      if (!this.phoneMixinInitialized) {
        if (this.getAllCountries !== 'undefined' && this.getAllCountries.length > 0) {
          this.phoneMixinInitialized = true
        } else {
          await this.loadAllCountries()
          this.phoneMixinInitialized = true
        }
      }
    },
    phoneNumber: function(countryId, mobileNumber, allCountry = false, reinitialize = true) {
      if (!this.$helpers.isEmpty(mobileNumber)) {
        if (reinitialize) {
          this.initPhoneMixin()
        }
        let country =
          (allCountry && this.getAllCountries.find(country => countryId === country.id)) ||
          this.getCountries.find(country => countryId === country.value)

        if (country) {
          mobileNumber = `(+${country.call_code}) ${mobileNumber}`
        }
        return mobileNumber
      } else {
        return ''
      }
    },
    countryCodePrefix: function(countryId) {
      return (
        '+' +
        (this.callCodeList !== undefined && countryId !== undefined
          ? (country => (country !== undefined ? country.call_code : ''))(
              this.callCodeList.find(item => item.value === countryId)
            )
          : '')
      )
    },
    phoneNumberMasking(countryId, phoneNumber) {
      let mobileNumber = this.phoneNumber(countryId, phoneNumber).replace(/\D/g, '')
      return '+' + mobileNumber.slice(-3).padStart(mobileNumber.length, 'x')
    },
  },
}
