<template>
  <div>
    <div>
      <v-row>
        <template v-if="!readonly">
          <template v-if="!$store.state.nativeDateTimeInput">
            <v-col xs6>
              <v-dialog v-model="dlgdate" width="300px">
                <template v-slot:activator="{ on }">
                  <v-text-field
                    dense
                    prepend-icon="$ayiCalendarAlt"
                    :value="readonlyDateFormat()"
                    :label="label"
                    :rules="rules"
                    readonly
                    :error="!!hasErrors"
                    v-on="on"
                    @click:prepend="dlgdate = true"
                  ></v-text-field>
                </template>
                <v-date-picker
                  dense
                  :value="dateValue"
                  :locale="languageName"
                  @input="updateDateValue"
                >
                  <v-btn text color="primary" @click="$emit('input', null)">{{
                    $ay.t("Delete")
                  }}</v-btn>
                  <v-spacer></v-spacer>
                  <v-btn text color="primary" @click="setToday()">{{
                    $ay.t("DateRangeToday")
                  }}</v-btn>
                  <v-spacer></v-spacer>
                  <v-btn text color="primary" @click="dlgdate = false">{{
                    $ay.t("OK")
                  }}</v-btn>
                </v-date-picker>
              </v-dialog>
            </v-col>
            <v-col xs6>
              <v-dialog v-model="dlgtime" width="300px">
                <template v-slot:activator="{ on }">
                  <v-text-field
                    dense
                    :value="readonlyTimeFormat()"
                    label
                    prepend-icon="$ayiClock"
                    readonly
                    :error="!!hasErrors"
                    v-on="on"
                    @click:prepend="dlgtime = true"
                  ></v-text-field>
                </template>
                <v-time-picker
                  dense
                  scrollable
                  ampm-in-title
                  :format="hour12 ? 'ampm' : '24hr'"
                  :value="timeValue"
                  @input="updateTimeValue"
                >
                  <v-btn text color="primary" @click="$emit('input', null)">{{
                    $ay.t("Delete")
                  }}</v-btn>
                  <v-spacer></v-spacer>
                  <v-btn text color="primary" @click="setNow()">{{
                    $ay.t("Now")
                  }}</v-btn>
                  <v-spacer></v-spacer>
                  <v-btn text color="primary" @click="dlgtime = false">{{
                    $ay.t("OK")
                  }}</v-btn>
                </v-time-picker>
              </v-dialog>
            </v-col>
          </template>
          <template v-if="$store.state.nativeDateTimeInput">
            <v-col cols="6">
              <v-text-field
                ref="dateField"
                dense
                :value="dateValue"
                :readonly="readonly"
                :disabled="disabled"
                :label="label"
                :rules="rules"
                type="date"
                :error-messages="errorMessages"
                :data-cy="`${dataCy}:date`"
                @change="updateDateValue"
              ></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field
                ref="timeField"
                dense
                :value="timeValue"
                :readonly="readonly"
                :disabled="disabled"
                type="time"
                :data-cy="`${dataCy}:time`"
                @change="updateTimeValue"
              ></v-text-field>
            </v-col>
          </template>
        </template>
        <template v-else>
          <v-col>
            <v-text-field
              dense
              :value="readonlyFormat()"
              :label="label"
              readonly
              prepend-icon="$ayiCalendarAlt"
            ></v-text-field>
          </v-col>
        </template>
      </v-row>
    </div>
    <div class="v-messages theme--light error--text mt-n5" role="alert">
      <div class="v-messages__wrapper">
        <div class="v-messages__message">{{ allErrors() }}</div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  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 },
    dataCy: { type: String, default: null }
  },
  data: () => ({
    nativeInput: true,
    dlgdate: false,
    dlgtime: false,
    timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
    languageName: window.$gz.locale.getResolvedLanguage(),
    hour12: window.$gz.locale.getHour12()
  }),
  computed: {
    hasErrors() {
      return this.errorMessages != null && this.errorMessages.length > 0;
    },
    timeValue() {
      return window.$gz.locale.utcDateStringToLocal8601TimeOnlyString(
        this.value,
        this.timeZoneName
      );
    },
    dateValue() {
      return window.$gz.locale.utcDateStringToLocal8601DateOnlyString(
        this.value,
        this.timeZoneName
      );
    }
  },
  methods: {
    setToday() {
      //Was this but in afternoon shows the next day ?!?
      // const v = window.$gz.locale
      //   .nowUTC8601String(this.timeZoneName)
      //   .split("T")[0];

      const v = window.$gz.DateTime.local()
        .toString()
        .split("T")[0];

      this.updateDateValue(v);
      this.dlgdate = false;
    },
    setNow() {
      //was this but works the more simpler way copied from set today
      //const v = window.$gz.locale.nowUTC8601String().split("T")[1];

      //now without the milliseconds
      var nowNoMs = window.$gz.DateTime.local().set({ milliseconds: 0 });
      const v = nowNoMs.toString().split("T")[1];

      this.updateTimeValue(v);
      this.dlgtime = false;
    },
    allErrors() {
      let ret = "";

      if (this.errorMessages != null && this.errorMessages.length > 0) {
        ret += this.errorMessages.toString();
      }
      return ret;
    },
    readonlyFormat() {
      return window.$gz.locale.utcDateToShortDateAndTimeLocalized(
        this.value,
        this.timeZoneName,
        this.languageName,
        this.hour12
      );
    },
    readonlyTimeFormat() {
      return window.$gz.locale.utcDateToShortTimeLocalized(
        this.value,
        this.timeZoneName,
        this.languageName,
        this.hour12
      );
    },
    readonlyDateFormat() {
      return window.$gz.locale.utcDateToShortDateLocalized(
        this.value,
        this.timeZoneName,
        this.languageName,
        this.hour12
      );
    },
    updateTimeValue(v) {
      this.updateValue(this.dateValue, v);
    },
    updateDateValue(v) {
      this.updateValue(v, this.timeValue);
      this.dlgdate = false;
    },
    updateValue(theDate, theTime) {
      const vm = this;
      if (!theDate) {
        const v = new Date();
        const 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();
        }
        theDate = fullYear + "-" + fullMonth + "-" + fullDay;
      }

      if (!theTime) {
        theTime = "00:00:00";
      }

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