<script setup lang="ts">
import {
  StoredObject,
  StoredObjectPointInTime,
  StoredObjectVersionWithPointInTime,
} from "ChillDocStoreAssets/types";
import UserRenderBoxBadge from "ChillMainAssets/vuejs/_components/Entity/UserRenderBoxBadge.vue";
import { ISOToDatetime } from "ChillMainAssets/chill/js/date";
import FileIcon from "ChillDocStoreAssets/vuejs/FileIcon.vue";
import RestoreVersionButton from "ChillDocStoreAssets/vuejs/StoredObjectButton/HistoryButton/RestoreVersionButton.vue";
import DownloadButton from "ChillDocStoreAssets/vuejs/StoredObjectButton/DownloadButton.vue";
import { computed } from "vue";

interface HistoryButtonListItemConfig {
  version: StoredObjectVersionWithPointInTime;
  storedObject: StoredObject;
  canEdit: boolean;
  isCurrent: boolean;
}

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

const props = defineProps<HistoryButtonListItemConfig>();

const onRestore = ({
  newVersion,
}: {
  newVersion: StoredObjectVersionWithPointInTime;
}) => {
  emit("restoreVersion", { newVersion });
};

const isKeptBeforeConversion = computed<boolean>(() => {
  if ("point-in-times" in props.version) {
    return props.version["point-in-times"].reduce(
      (accumulator: boolean, pit: StoredObjectPointInTime) =>
        accumulator || "keep-before-conversion" === pit.reason,
      false,
    );
  } else {
    return false;
  }
});

const isRestored = computed<boolean>(
  () => props.version.version > 0 && null !== props.version["from-restored"],
);

const isDuplicated = computed<boolean>(
  () => props.version.version === 0 && null !== props.version["from-restored"],
);

const classes = computed<{
  row: true;
  "row-hover": true;
  "blinking-1": boolean;
  "blinking-2": boolean;
}>(() => ({
  row: true,
  "row-hover": true,
  "blinking-1": props.isRestored && 0 === props.version.version % 2,
  "blinking-2": props.isRestored && 1 === props.version.version % 2,
}));
</script>

<template>
  <div :class="classes">
    <div
      class="col-12 tags"
      v-if="isCurrent || isKeptBeforeConversion || isRestored || isDuplicated"
    >
      <span class="badge bg-success" v-if="isCurrent">Version actuelle</span>
      <span class="badge bg-info" v-if="isKeptBeforeConversion"
        >Conservée avant conversion dans un autre format</span
      >
      <span class="badge bg-info" v-if="isRestored"
        >Restaurée depuis la version
        {{ version["from-restored"]?.version + 1 }}</span
      >
      <span class="badge bg-info" v-if="isDuplicated"
        >Dupliqué depuis un autre document</span
      >
    </div>
    <div class="col-12">
      <file-icon :type="version.type"></file-icon>
      <span
        ><strong>&nbsp;#{{ version.version + 1 }}&nbsp;</strong></span
      >
      <template v-if="version.createdBy !== null && version.createdAt !== null"
        ><strong v-if="version.version == 0">créé par</strong
        ><strong v-else>modifié par</strong>
        <span class="badge-user"
          ><UserRenderBoxBadge :user="version.createdBy"></UserRenderBoxBadge
        ></span>
        <strong>à</strong>
        {{
          $d(ISOToDatetime(version.createdAt.datetime8601), "long")
        }}</template
      ><template v-if="version.createdBy === null && version.createdAt !== null"
        ><strong v-if="version.version == 0">Créé le</strong
        ><strong v-else>modifié le</strong>
        {{
          $d(ISOToDatetime(version.createdAt.datetime8601), "long")
        }}</template
      >
    </div>
    <div class="col-12">
      <ul class="record_actions small slim on-version-actions">
        <li v-if="canEdit && !isCurrent">
          <restore-version-button
            :stored-object-version="props.version"
            @restore-version="onRestore"
          ></restore-version-button>
        </li>
        <li>
          <download-button
            :stored-object="storedObject"
            :at-version="version"
            :classes="{
              btn: true,
              'btn-outline-primary': true,
              'btn-sm': true,
            }"
            :display-action-string-in-button="false"
          ></download-button>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped lang="scss">
div.tags {
  span.badge:not(:last-child) {
    margin-right: 0.5rem;
  }
}
// to make the animation restart, we have the same animation twice,
// and alternate between both
.blinking-1 {
  animation-name: backgroundColorPalette-1;
  animation-duration: 8s;
  animation-iteration-count: 1;
  animation-direction: normal;
  animation-timing-function: linear;
}
@keyframes backgroundColorPalette-1 {
  0% {
    background: var(--bs-chill-green-dark);
  }
  25% {
    background: var(--bs-chill-green);
  }
  65% {
    background: var(--bs-chill-beige);
  }
  100% {
    background: unset;
  }
}
.blinking-2 {
  animation-name: backgroundColorPalette-2;
  animation-duration: 8s;
  animation-iteration-count: 1;
  animation-direction: normal;
  animation-timing-function: linear;
}
@keyframes backgroundColorPalette-2 {
  0% {
    background: var(--bs-chill-green-dark);
  }
  25% {
    background: var(--bs-chill-green);
  }
  65% {
    background: var(--bs-chill-beige);
  }
  100% {
    background: unset;
  }
}
</style>
