<script>
// https://date-fns.org/docs
import { format, parse, distanceInWords, isPast, is, today } from 'date-fns';

export default {
  name: 'EbDate',
  props: {
    date: {
      type: [Date, String],
      default: null
    },
    time: {
      type: [String, Number],
      default: null
    },
    format: {
      type: String,
      default: 'MMM Do, YYYY h:mmA'
    },
    display: {
      type: String,
      default: 'datetime',
      validator: val =>
        ['date', 'datetime', 'relative'].includes(val.toLowerCase())
    },
    compareDate: {
      type: [Date, String],
      default: () => {
        return new Date();
      }
    }
  },

  methods: {
    formatDateRelative(fromDate, toDate = new Date()) {
      return distanceInWords(parse(toDate), parse(fromDate), {
        includeSeconds: true,
        addSuffix: true
      });
    },

    formatDateTime(date, dateFormat = 'MMM Do, YYYY h:mmA') {
      return format(parse(date), dateFormat);
    },

    formatDateOnly(date, dateFormat = 'MMM Do, YYYY') {
      return format(parse(date), dateFormat);
    }
  },

  computed: {
    displayDate() {
      if (this.date === null) return 'Date not Specified.';

      if (this.display === 'relative')
        return this.formatDateRelative(this.dateTime, this.compareDate);

      return this.display === 'date'
        ? this.formatDateOnly(this.dateTime)
        : this.formatDateTime(this.dateTime, this.format);
    },

    dateTime() {
      if (this.time === null || this.display === 'date') return this.date;
      return this.date + 'T' + this.time;
    }
  },
  render(createElement) {
    return createElement(
      'span',
      {
        on: this.$attrs,
        bind: this.$listeners
      },
      this.displayDate
    );
  }
};
</script>
