<template>
  <div>
    <template v-if="!readonly">
      <v-text-field
        ref="dateField"
        :value="dateValue"
        @change="updateValue()"
        :readonly="readonly"
        :disabled="disabled"
        :label="label"
        :rules="rules"
        type="date"
        :error-messages="errorMessages"
        :data-cy="'dateinput:' + testId"
      ></v-text-field>
    </template>
    <template v-else>
      <v-text-field
        :value="readonlyFormat()"
        :label="label"
        readonly
      ></v-text-field>
    </template>
  </div>
</template>
<script>
/*  Xeslint-disable */
export default {
  data() {
    return {
      timeZoneName: window.$gz.locale.getBrowserTimeZoneName()
    };
  },
  props: {
    label: String,
    rules: Array,
    errorMessages: { type: Array, default: null },
    value: { type: String, default: null },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    testId: String
  },
  computed: {
    dateValue() {
      return window.$gz.locale.utcDateStringToLocal8601DateOnlyString(
        this.value,
        this.timeZoneName
      );
    }
  },
  methods: {
    readonlyFormat() {
      return window.$gz.locale.utcDateToShortDateLocalized(
        this.internalValue,
        this.timeZoneName,
        this.languageName,
        this.hour12
      );
    },
    updateValue() {
      let vm = this;
      let dateValue = vm.$refs.dateField.$refs.input.value;
      if (!dateValue) {
        let v = new Date();
        let fullYear = v.getFullYear();
        let fullMonth = v.getMonth() + 1;
        if (fullMonth < 10) {
          fullMonth = "0" + fullMonth.toString();
        }
        let fullDay = v.getDate();
        if (fullDay < 10) {
          fullDay = "0" + fullDay.toString();
        }
        dateValue = fullYear + "-" + fullMonth + "-" + fullDay;
      }

      let timeValue = window.$gz.locale.utcDateStringToLocal8601TimeOnlyString(
        vm.value,
        vm.timeZoneName
      );
      if (!timeValue) {
        timeValue = "00:00:00";
      }

      let ret = window.$gz.locale.localTimeDateStringToUTC8601String(
        dateValue + "T" + timeValue,
        vm.timeZoneName
      );
      vm.$emit("input", ret);
    }
  }
};
</script>
