<template>
  <v-row>
    <template v-if="!readonly">
      <v-col cols="6">
        <v-text-field
          ref="dateField"
          :value="splitValue.date"
          @change="updateValue()"
          :readonly="readonly"
          :disabled="disabled"
          :label="label"
          :rules="rules"
          type="date"
          :error-messages="errorMessages"
          :data-cy="'dateinput:' + testId"
        ></v-text-field>
      </v-col>
      <v-col cols="6">
        <v-text-field
          ref="timeField"
          :value="splitValue.time"
          @change="updateValue()"
          :readonly="readonly"
          :disabled="disabled"
          type="time"
          :data-cy="'timeinput:' + testId"
        ></v-text-field>
      </v-col>
    </template>
    <template v-else>
      <v-text-field
        :value="readonlyFormat()"
        :label="label"
        readonly
      ></v-text-field>
    </template>
  </v-row>
</template>
<script>
//==========================================
//==========================================
export default {
  data() {
    return {
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName()
    };
  },

  props: {
    label: { type: String, default: null },
    rules: { type: Array, default: undefined},
    errorMessages: { type: Array, default: null },
    value: { type: String, default: null },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    testId: { type: String, default: null }
  },
  computed: {
    splitValue() {
      return {
        date: window.$gz.locale.utcDateStringToLocal8601DateOnlyString(
          this.value,
          this.timeZoneName
        ),
        time: window.$gz.locale.utcDateStringToLocal8601TimeOnlyString(
          this.value,
          this.timeZoneName
        )
      };
    }
  },
  methods: {
    readonlyFormat() {
      return window.$gz.locale.utcDateToShortDateAndTimeLocalized(
        this.value,
        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 = vm.$refs.timeField.$refs.input.value;
      if (!timeValue) {
        timeValue = "00:00:00";
      }

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