<template>
  <div>
    <v-text-field
      ref="textField"
      v-currency="{
        currency: currencyName,
        locale: languageName
      }"
      dense
      :value="currencyValue"
      :readonly="readonly"
      :disabled="disabled"
      :label="label"
      :rules="rules"
      :error-messages="errorMessages"
      :append-outer-icon="appendOuterIcon"
      @input="updateValue"
      @click:append-outer="$emit('gz-append-outer')"
    ></v-text-field>
  </div>
</template>
<script>
//https://dm4t2.github.io/vue-currency-input/guide/#introduction :value="formattedValue"
//https://codesandbox.io/s/vue-template-kd7d1?fontsize=14&module=%2Fsrc%2FApp.vue
//https://github.com/dm4t2/vue-currency-input
//https://github.com/dm4t2/vue-currency-input/releases

//NOTE: when get sick of this not working, can look into this: https://github.com/phiny1/v-currency-field
//which is purported to be exactly what I'm trying to do here with a v-text-field but better I guess??
//or look at the source for ideas?

import { parse } from "vue-currency-input";
export default {
  props: {
    label: { type: String, default: null },
    rules: { type: Array, default: undefined },
    value: { type: Number, default: null },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    errorMessages: { type: Array, default: null },
    appendOuterIcon: { type: String, default: null }
  },
  data() {
    return {
      currencyName: window.$gz.locale.getCurrencyName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      initializing: true
    };
  },
  computed: {
    currencyValue() {
      return this.value;
    }
  },
  methods: {
    updateValue() {
      //this is required because the initial setting triggers an input event
      //however the two values differ because it comes from the server in much higher precision
      //and this control rounds it down
      //so the first trigger must be ignored until it "settles"
      if (this.initializing) {
        this.initializing = false;
        return;
      }
      const val = this.$refs.textField.$refs.input.value;

      const parsedValue = parse(val, {
        currency: this.currencyName,
        locale: this.languageName
      });

      if (parsedValue != this.value) {
        this.$emit("input", parsedValue);
      }
    }
  }
};
</script>
