<script>
import { formatDate } from '~/lib/utils/datetime_utility';
import IncidentTimelineEventListItem from './timeline_events_list_item.vue';

export default {
  name: 'IncidentTimelineEventList',
  components: {
    IncidentTimelineEventListItem,
  },
  props: {
    timelineEventLoading: {
      type: Boolean,
      required: false,
      default: true,
    },
    timelineEvents: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  computed: {
    dateGroupedEvents() {
      const groupedEvents = new Map();

      this.timelineEvents.forEach((event) => {
        const date = formatDate(event.occurredAt, 'isoDate', true);

        if (groupedEvents.has(date)) {
          groupedEvents.get(date).push(event);
        } else {
          groupedEvents.set(date, [event]);
        }
      });

      return groupedEvents;
    },
  },
  methods: {
    isLastItem(groups, groupIndex, events, eventIndex) {
      if (groupIndex < groups.size - 1) {
        return false;
      }
      return eventIndex === events.length - 1;
    },
  },
};
</script>

<template>
  <div class="issuable-discussion incident-timeline-events">
    <div
      v-for="([eventDate, events], groupIndex) in dateGroupedEvents"
      :key="eventDate"
      data-testid="timeline-group"
    >
      <div class="gl-pb-3 gl-border-gray-50 gl-border-1 gl-border-b-solid">
        <strong class="gl-font-size-h2" data-testid="event-date">{{ eventDate }}</strong>
      </div>
      <ul class="notes main-notes-list gl-pl-n3">
        <incident-timeline-event-list-item
          v-for="(event, eventIndex) in events"
          :key="event.id"
          :action="event.action"
          :occurred-at="event.occurredAt"
          :note-html="event.noteHtml"
          :is-last-item="isLastItem(dateGroupedEvents, groupIndex, events, eventIndex)"
          data-testid="timeline-event"
        />
      </ul>
    </div>
  </div>
</template>
