<script setup lang="ts">
import {
  StoredObject,
  StoredObjectVersionWithPointInTime,
} from "./../../../types";
import HistoryButtonListItem from "ChillDocStoreAssets/vuejs/StoredObjectButton/HistoryButton/HistoryButtonListItem.vue";
import { computed, reactive } from "vue";

interface HistoryButtonListConfig {
  versions: StoredObjectVersionWithPointInTime[];
  storedObject: StoredObject;
  canEdit: boolean;
}

const emit = defineEmits<{
  restoreVersion: [newVersion: StoredObjectVersionWithPointInTime];
}>();

interface HistoryButtonListState {
  /**
   * Contains the number of the newly created version when a version is restored.
   */
  restored: number;
}

const props = defineProps<HistoryButtonListConfig>();

const state = reactive<HistoryButtonListState>({ restored: -1 });

const higher_version = computed<number>(() =>
  props.versions.reduce(
    (accumulator: number, version: StoredObjectVersionWithPointInTime) =>
      Math.max(accumulator, version.version),
    -1,
  ),
);

/**
 * Executed when a version in child component is restored.
 *
 * internally, keep track of the newly restored version
 */
const onRestored = ({
  newVersion,
}: {
  newVersion: StoredObjectVersionWithPointInTime;
}) => {
  state.restored = newVersion.version;
  emit("restoreVersion", { newVersion });
};
</script>

<template>
  <template v-if="props.versions.length > 0">
    <div class="container">
      <template v-for="v in props.versions" :key="v.id">
        <history-button-list-item
          :version="v"
          :can-edit="canEdit"
          :is-current="higher_version === v.version"
          :stored-object="storedObject"
          @restore-version="onRestored"
        ></history-button-list-item>
      </template>
    </div>
  </template>
  <template v-else>
    <p>Chargement des versions</p>
  </template>
</template>

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