import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'messageTime',
    standalone: true
})
export class MessageTimePipe implements PipeTransform {

  transform(someDateTimeStamp: string): void | string {
    if (someDateTimeStamp) {
      const dt = new Date(someDateTimeStamp);
      const today = new Date();
      const yesterday = new Date(Date.now() - 86400000);
      if (dt.getDate() === today.getDate() &&
        dt.getMonth() === today.getMonth() &&
        dt.getFullYear() === today.getFullYear()) {
        return this.formatAMPM(dt);
      } else if (dt.getDate() === yesterday.getDate() &&
        dt.getMonth() === yesterday.getMonth() &&
        dt.getFullYear() === yesterday.getFullYear()) {
        return 'Yesterday';
      } else if (this.getDaysDifferenceFromToday(dt) <= 7) {
        return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dt.getDay()];
      } else {
        return this.getMMDDYYFormat(dt);
      }
    }
  }

  formatAMPM(date: Date) {
    let hours = date.getHours();
    let minutes = date.getMinutes().toString();
    const ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = (+minutes) < 10 ? '0' + minutes : minutes;
    const strTime = hours + ':' + minutes + ' ' + ampm;
    return strTime;
  }

  getDaysDifferenceFromToday(date2: Date) {
    const diffTime = Math.abs(date2.valueOf() - new Date().valueOf());
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }

  getMMDDYYFormat(date: Date) {
    return ('0' + (date.getMonth() + 1)).slice(-2) + '/' +
      ('0' + date.getDate()).slice(-2) + '/' +
      date.getFullYear().toString().slice(2);
  }

}
