<script setup>
import "@vuepic/vue-datepicker/dist/main.css";
import { computed, onMounted, ref } from "vue";
import { VTextField } from "vuetify/components/VTextField";
import { isArray } from "lodash-es";
const props = defineProps({
  flow: { type: Array, required: false, default: () => ["year", "month", "calendar"] },
  dobPrecisionText: { type: Object, required: false },
  rules: { type: null, required: false }
});
const emit = defineEmits(["update:modelValue"]);
const modelValue = defineModel({ type: String });
const dobPrecisionText = computed(() => {
  if (props.dobPrecisionText) return props.dobPrecisionText;
  else return {
    yearMonthDay: "YMD",
    yearMonth: "YM",
    year: "Y",
    estimated: "EST"
  };
});
const dobPrecisionChoice = ref(["yearMonthDay", "yearMonth", "year", "estimated"]);
const dobPrecisionSelected = defineModel("dobPrecision", { type: String });
onMounted(() => {
  if (!dobPrecisionSelected.value) {
    dobPrecisionSelected.value = "yearMonthDay";
  }
});
const dobPrecisionDisplay = computed(() => {
  return dobPrecisionSelected.value ? dobPrecisionText.value[dobPrecisionSelected.value] : dobPrecisionText.value["yearMonthDay"];
});
const changeDobPrecision = () => {
  if (dobPrecisionSelected.value && dobPrecisionChoice.value.includes(dobPrecisionSelected.value)) {
    dobPrecisionSelected.value = dobPrecisionChoice.value[(dobPrecisionChoice.value.indexOf(dobPrecisionSelected.value) + 1) % dobPrecisionChoice.value.length];
  } else {
    dobPrecisionSelected.value = dobPrecisionChoice.value[0];
  }
};
const computedRules = computed(() => {
  if (props.rules && isArray(props.rules)) {
    return props.rules.includes("DateHappen") ? props.rules : props.rules.concat("DateHappen");
  } else {
    return ["DateHappen"];
  }
});
const dobFormat = computed(() => {
  let displayFormat = void 0;
  if (dobPrecisionSelected.value == "yearMonth") {
    displayFormat = "MMM yyyy";
  }
  if (dobPrecisionSelected.value == "year") {
    displayFormat = "yyyy";
  }
  if (dobPrecisionSelected.value == "estimated") {
    displayFormat = "~ MMM yyyy";
  }
  return displayFormat;
});
</script>

<template>
  <FormDate
      v-model="modelValue"
      :flow="props.flow"
      :format="dobFormat"
      :rules="computedRules"
  >
    <template #append="{ isReadonly, isDisabled, activatorProps, toggleMenuOpen }">
      <span
          style="cursor: pointer;"
          class="font-weight-medium"
          @click="isReadonly.value || isDisabled.value ? void 0 : changeDobPrecision()"
      >{{ dobPrecisionDisplay }}</span>
      &nbsp;
      <v-icon
          :disabled="isReadonly.value || isDisabled.value"
          v-bind="activatorProps"
          @click="toggleMenuOpen('icon')"
      >
        fa:fa-regular fa-calendar
      </v-icon>
    </template>
  </FormDate>
</template>
