<template>
  <widget-wrapper v-bind="$props" v-slot="{ inputEvents }">
    <arm-datepicker
      ref="armDatepicker"
      :type="type"
      v-bind="props"
      :value="valueId"
      :noLabels="noLabels"
      :label="fieldNode.label"
      :color="color"
      :validationError="hasError"
      :validationMessage="errorMessage"
      :fg-error-message="props.errorMessage"
      :required="fieldNode.mandatory"
      :readonly="isReadonly"
      :disable="disable"
      :steppedBack="steppedBack"
      @input="inputEvents.input"
      @focus="onFocus"
      class="date-input"
    />
  </widget-wrapper>
</template>

<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import {
  ValidatedField,
  FormGeneratorDateType,
  WidgetWrapper,
  FormWidget,
} from '@devsun/form-generator/dist';
import ArmDatepicker from '../datepicker/arm-datepicker.vue';
import ArmDatepickerClass from '../datepicker/arm-datepicker';
import { convertDateFormat } from '@utils/format-date';

@Component({
  components: {
    ArmDatepicker,
    WidgetWrapper,
  },
})
export default class DateInput extends mixins(FormWidget, ValidatedField) {
  @Prop({ default: FormGeneratorDateType.none }) type!: FormGeneratorDateType;
  @Prop() setDefault: string;
  @Prop() format: string;
  @Prop() maxToday: boolean;

  mounted(): void {
    this.setDefaultDate();
  }

  get isClearModalOpen(): boolean {
    return this.$store.getters['formGenerator/isClearModalOpen'];
  }

  get steppedBack(): boolean {
    return this.$store.getters['formGenerator/steppedBack'];
  }

  get disable(): boolean {
    return this.isClearModalOpen;
  }

  get props() {
    return this.fieldNode?.rawAttrs?.props || undefined;
  }

  @Watch('props', { deep: true })
  onPropsChange(): void {
    this.setDefaultDate();
  }

  get valueId(): string {
    return this.value && (this.value.__id as string);
  }

  get isReadonly(): boolean {
    if (this.fieldNode.simlink) {
      return true;
    }
    return !!this.fieldNode.readonly;
  }

  get fieldClasses() {
    return {
      editable: !this.fieldNode.readonly,
      'label-uppercase': false,
      dense: this.isDense,
    };
  }

  setDefaultDate(): void {
    if (this.value.__id) return;

    const props = this.fieldNode?.rawAttrs?.props;
    const armDatepicker = this.$refs.armDatepicker as ArmDatepickerClass;

    if (!props?.setDefault) return;

    switch (props.setDefault) {
      case 'today':
        const today = convertDateFormat(new Date(), '', armDatepicker.pattern);

        this.$nextTick(() => {
          armDatepicker.onManualInput(today, void 0);
        })

        break;
    }
  }

  onFocus(): void {
    this.$store.commit('formGenerator/setClearModal', true);
  }
}
</script>

<style scoped>
.date-input {
  margin-top: 12px;
  padding-bottom: 20px;
}
</style>
