<template>
  <div class="d-flex">
    <v-text-field type="number" min="1" max="31" v-model="day" :label="weekday" :hide-details="hideDetails" style="min-width: 3em; width: 3em" class="all"/>
    <v-select v-model="month" :items="monthItems" :hide-details="hideDetails" style="min-width: 6em; width: 6em" class="all"/>
    <v-text-field type="number" v-model="year" :hide-details="hideDetails" style="min-width: 5em; width: 5em" class="all"/>
    <v-text-field type="time" v-model="time" :hide-details="hideDetails" style="min-width: 8em; width: 8em" class="all"/>
  </div>
</template>

<script setup>
import {useStore} from "@/store/store";
import {computed} from "vue";

const s = useStore()
const props = defineProps(['modelValue', 'hideDetails'])
const emit = defineEmits(['update:modelValue'])

const day = computed({
  get() { return s.utc ? props.modelValue.getUTCDate() : props.modelValue.getDate() },
  set(v) { update(year.value, month.value, v, time.value)},
})
const weekdayFormat = computed(()=>new Intl.DateTimeFormat(s.utc ? 'utc':undefined,{weekday:"short"}))
const weekday = computed(()=>weekdayFormat.value.format(props.modelValue))
const month = computed({
  get() { return s.utc ? props.modelValue.getUTCMonth() : props.modelValue.getMonth() },
  set(v) { update(year.value, v, day.value, time.value)},
})
const year = computed({
  get() { return s.utc ? props.modelValue.getUTCFullYear() : props.modelValue.getFullYear() },
  set(v) { update(v, month.value, day.value, time.value)},
})
const time = computed({
  get() {
    let hour, min
    if( s.utc ) {
      hour = props.modelValue.getUTCHours()
      min = props.modelValue.getUTCMinutes()
    }
    else {
      hour = props.modelValue.getHours()
      min = props.modelValue.getMinutes()
    }
    return hour.toString().padStart(2,'0') + ':' + min.toString().padStart(2,'0')
  },
  set(v) { update(year.value, month.value, day.value, v) }
})

function monthsForLocale(localeName = undefined, monthFormat = 'long') {
  const format = new Intl.DateTimeFormat(localeName, {month: monthFormat}).format;
  return [...Array(12).keys()]
      .map((m) => format(new Date(Date.UTC(2000, m+1))));
}

let m=0
const monthItems = monthsForLocale(undefined, 'short').map((v)=>{return {title:v, value:m++}})

function buildDate(y, m, d, t) {
  const [hours,minutes] = t.split(':')
  return s.utc ? new Date(Date.UTC(y, m, d, hours, minutes))
      : new Date(y, m, d, hours, minutes);
}

function update(y,m,d,t) {
  const date = buildDate(y, m, d, t);
  emit('update:modelValue', date)
}
</script>

<style scoped lang="scss">
@use "src/styles/vars" as *;

.all {
  margin-bottom: 0;
}
</style>
