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

interface HistoryButtonConfig {
  storedObject: StoredObject;
  canEdit: boolean;
}

interface HistoryButtonState {
  versions: StoredObjectVersionWithPointInTime[];
  loaded: boolean;
}

const props = defineProps<HistoryButtonConfig>();
const state = reactive<HistoryButtonState>({ versions: [], loaded: false });
const modal = useTemplateRef<typeof HistoryButtonModal>("modal");

const download_version_and_open_modal = async function (): Promise<void> {
  if (null !== modal.value) {
    modal.value.open();
  } else {
    console.log("modal is null");
  }

  if (!state.loaded) {
    const versions = await get_versions(props.storedObject);

    for (const version of versions) {
      state.versions.push(version);
    }
    state.loaded = true;
  }
};

const onRestoreVersion = ({
  newVersion,
}: {
  newVersion: StoredObjectVersionWithPointInTime;
}) => {
  state.versions.unshift(newVersion);
};
</script>

<template>
  <a @click="download_version_and_open_modal" class="dropdown-item">
    <history-button-modal
      ref="modal"
      :versions="state.versions"
      :stored-object="storedObject"
      :can-edit="canEdit"
      @restore-version="onRestoreVersion"
    ></history-button-modal>
    <i class="fa fa-history"></i>
    Historique
  </a>
</template>

<style scoped lang="scss">
i.fa::before {
  color: var(--bs-dropdown-link-hover-color);
}
</style>
