<template>
  <div>
    <template v-if="!readonly">
      <v-text-field
        ref="timeField"
        :value="timeControlFormat()"
        @input="handleTimeInput"
        :readonly="readonly"
        :disabled="disabled"
        :label="label"
        :rules="rules"
        :error-messages="allErrors()"
        type="time"
        :data-cy="!!$ay.dev ? 'timeinput:' + testId : false"
      ></v-text-field>
    </template>
    <template v-else>
      <v-text-field
        :value="readonlyFormat()"
        :label="label"
        readonly
        disabled
      ></v-text-field>
    </template>
  </div>
</template>

<script>
//==========================================
//==========================================
export default {
  data() {
    return {
      internalValue: null,
      timeZoneName: window.$gz.locale.getBrowserTimeZoneName()
    };
  },
  watch: {
    value(val) {
      this.internalValue = val;
    }
  },
  props: {
    label: String,
    rules: Array,
    "error-messages": { type: Array, default: null },
    value: { type: String, default: null },
    readonly: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    error: {
      type: String,
      required: false
    },
    testId: String
  },
  methods: {
    allErrors() {
      let ret = "";
      if (this.error != null) {
        ret = this.error;
      }
      if (this.errorMessages != null && this.errorMessages.length > 0) {
        ret += this.errorMessages.toString();
      }
      return ret;
    },
    readonlyFormat() {
      return window.$gz.locale.utcDateToShortTimeLocalized(
        this.internalValue,
        this.timeZoneName,
        this.languageName,
        this.hour12
      );
    },
    timeControlFormat() {
      //hh:mm:ss in 24 hour format
      return window.$gz.locale.utcDateStringToLocal8601TimeOnlyString(
        this.internalValue,
        this.timeZoneName
      );
    },
    handleTimeInput(value) {
      let DatePortion = window.$gz.locale.utcDateStringToLocal8601DateOnlyString(
        this.internalValue,
        this.timeZoneName
      );
      if (!DatePortion) {
        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();
        }
        DatePortion = fullYear + "-" + fullMonth + "-" + fullDay;
      }
      let newValue = window.$gz.locale.localTimeDateStringToUTC8601String(
        DatePortion + "T" + value,
        this.timeZoneName
      );
      this.$emit("input", newValue);
    }
  }
};
</script>
