<template>
  <div class="itf-periodpicker">
    <input
      ref="input"
      readonly
      class="form-control"
      :class="{ 'is-invalid': isInvalid(), 'is-valid': isSuccess() }"
      @focus="onFocus"
      @blur="onBlur"
      :value="displayText"
      :placeholder="placeholder"
    />
    <div style="display: none">
      <itf-period-picker-inline
        ref="dropdown"
        class="itf-periodpicker__dropdown"
        v-model="value"
        :value-format="valueFormat"
        @input="onInput"
      />
    </div>
  </div>
</template>
<script>
import { Vue, Component, Prop, Inject } from 'vue-property-decorator';
import tippy from 'tippy.js';
import itfPeriodPickerInline from "./PeriodPickerInline.vue";
import {DateTime} from "luxon";
import ITFSettings from '../../ITFSettings';

export default @Component({
  name: 'itfPeriodPicker',
  components: {
    itfPeriodPickerInline
  }
})
class itfPeriodPicker extends Vue {
  @Inject({ default: null }) itemLabel;

  @Prop({ type: Array }) value;
  @Prop({ type: String, default: 'ISO' }) valueFormat;
  @Prop({ type: String, default: 'bottom-start' }) placement;
  @Prop({ type: String, default: '' }) placeholder;
  @Prop({ type: String }) displayFormat;

  focused = false;

  mounted() {
    const context = this.$el.closest('.itf-append-context') || document.body;
    this.tooltip = tippy(this.$refs.input, {
      interactiveBorder: 30,
      interactiveDebounce: 75,
      animation: 'scale',
      arrow: true,
      content: this.$refs.dropdown.$el,
      allowHTML: true,
      trigger: 'click',
      interactive: true,
      placement: this.placement,
      appendTo: context,
    });
  }

  get dateFormat() {
    return this.displayFormat || ITFSettings.defaultDisplayDateFormat;
  }

  get displayText() {
    return this.displayValue.join(' - ');
  }

  get displayValue() {
    if (!this.valueAsLuxon || this.valueAsLuxon.length < 2) {
      return [];
    }
    console.info(this.valueAsLuxon);
    return [
      this.valueAsLuxon[0].toFormat(this.dateFormat),
      this.valueAsLuxon[1].toFormat(this.dateFormat)
    ];
  }

  get valueAsLuxon() {
    if (!this.value || this.value.length < 2) {
      return null;
    }
    if (this.valueFormat === 'ISO') {
      return [
        DateTime.fromISO(this.value[0]),
        DateTime.fromISO(this.value[1]),
      ];
    }
    return [
      DateTime.fromFormat(this.value[0], this.valueFormat),
      DateTime.fromFormat(this.value[1], this.valueFormat),
    ];
  }

  onFocus() {
    this.focused = true;
  }

  onBlur(e) {
    this.focused = false;
  }

  isInvalid() {
    return this.itemLabel && this.itemLabel.isHasError();
  }

  isSuccess() {
    return this.itemLabel && this.itemLabel.isHasSuccess();
  }

  selectInlineDate(date) {
    this.$emit('input', date);
  }

  onInput(val) {
    this.$emit('input', val);
    this.tooltip.hide();
  }
}
</script>
