<script setup lang="ts">
import { useIntervalFn } from "@vueuse/core";
import { fetchWorkflow } from "ChillMainAssets/lib/workflow/api";
import { returnPathOr } from "ChillMainAssets/lib/return_path/returnPathHelper";
import { ref } from "vue";
import WaitingScreen from "ChillMainAssets/vuejs/_components/WaitingScreen.vue";
import { WaitingScreenState } from "ChillMainAssets/types";
import {
  trans,
  WORKFLOW_WAIT_TITLE,
  WORKFLOW_WAIT_ERROR_WHILE_WAITING,
  WORKFLOW_WAIT_SUCCESS,
} from "translator";

interface WaitPostProcessWorkflowComponentProps {
  workflowId: number;
  expectedStep: string;
}

const props = defineProps<WaitPostProcessWorkflowComponentProps>();
const counter = ref<number>(0);
const MAX_TRYIES = 50;

const state = ref<WaitingScreenState>("pending");

const { pause, resume } = useIntervalFn(
  async () => {
    try {
      const workflow = await fetchWorkflow(props.workflowId);
      counter.value++;
      if (workflow.currentStep.currentStep.name === props.expectedStep) {
        window.location.assign(
          returnPathOr("/fr/main/workflow" + workflow.id + "/show"),
        );
        resume();
        state.value = "ready";
      }

      if (counter.value > MAX_TRYIES) {
        pause();
        state.value = "failure";
      }
    } catch (error) {
      console.error(error);
      pause();
    }
  },
  2000,
  { immediate: true },
);
</script>

<template>
  <div class="container">
    <WaitingScreen :state="state">
      <template v-slot:pending>
        <p>
          {{ trans(WORKFLOW_WAIT_TITLE) }}
        </p>
      </template>
      <template v-slot:failure>
        <p>
          {{ trans(WORKFLOW_WAIT_ERROR_WHILE_WAITING) }}
        </p>
      </template>
      <template v-slot:ready>
        <p>
          {{ trans(WORKFLOW_WAIT_SUCCESS) }}
        </p>
      </template>
    </WaitingScreen>
  </div>
</template>

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