<template>
  <div>
    <v-text-field
      ref="textField"
      @input="handleInput"
      v-currency="{
        currency: currencyName,
        locale: languageName
      }"
      :readonly="readonly"
      :disabled="disabled"
      :label="label"
      :rules="rules"
    ></v-text-field>
    <p v-show="error" class="form__error v-messages theme--light error--text">
      {{ error }}
    </p>
  </div>
</template>
<script>
/*  Xeslint-disable */
//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
import { setValue, parseCurrency } from "vue-currency-input";
export default {
  data() {
    return {
      internalValue: null,
      internalChange: false,
      currencyName: window.$gz.locale.getCurrencyName(),
      languageName: window.$gz.locale.getBrowserFirstLanguage()
    };
  },
  watch: {
    value(val) {
      this.internalChange = true;
      setValue(this.$refs.textField.$refs.input, val);
    }
  },
  props: {
    label: String,
    rules: Array,
    value: { type: Number, default: null },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    error: {
      type: String,
      required: false
    }
  },
  methods: {
    handleInput(value) {
      let parsedValue = parseCurrency(value, {
        currency: this.currencyName,
        locale: this.languageName
      });
      if (this.internalChange) {
        this.internalValue = parsedValue;
        this.internalChange = false;
        return;
      }

      if (parsedValue == this.internalValue) {
        //nothing changed
        return;
      }

      this.$emit("input", parsedValue);
      this.internalValue = parsedValue;
    }
  }
};
</script>
