<template>
  <span :title="fullString">{{ friendlyString }}</span>
</template>

<script>

  export default {
    props: {
      dateTime: {
        required: true,
        type: [Date, String]
      },

      showDate: {
        required: false,
        type: Boolean,
        default: true
      },

      showTime: {
        required: false,
        type: Boolean,
        default: true
      }
    },

    computed: {
      dateObj() {
        if (this.dateTime instanceof Date) {
          return this.dateTime;
        } else if (this.dateTime === null || this.dateTime.length === 0) {
          return null;
        } else {
          return new Date(this.dateTime);
        }
      },

      friendlyString() {
        const parts = [];
        if (this.showDate) {
          parts.push(this.formatDate());
        }
        if (this.showTime) {
          parts.push(this.formatTime(true));
        }
        return parts.join(" ");
      },

      fullString() {
        return this.formatDate() + " " + this.formatTime(false);
      }
    },

    methods: {
      formatDate() {
        if (this.dateObj) {
          return [this.dateObj.getMonth() + 1, this.dateObj.getDate(), this.dateObj.getFullYear() % 100].join("/");
        } else {
          return "";
        }
      },

      formatTime(use12hour) {
        if (this.dateObj) {
          let h = this.dateObj.getHours();
          const m = this.dateObj.getMinutes().toString().padStart(2, "0");
          let meridiem = "";

          if (use12hour) {
            meridiem = " am";

            if (h === 0) {
              h = 12;
            } else if (h > 12) {
              h = h - 12;
              meridiem = " pm";
            }
          } else {
            h = h.toString().padStart(2, "0");
          }

          return h + ":" + m + meridiem;

        } else {
          return "";
        }
      }
    }
  }

</script>

<style lang="scss" scoped>
</style>