<template>
  <div
    class="border-yellow-300 p-8 border-t-8 bg-white mb-6 rounded-lg shadow-lg text-left"
  >
    <span class="block w-full text-3xl mb-4" v-text="apName" />

    <div v-if="stateOfTask.result === undefined" class="relative pt-1">
      <div class="flex mb-2 items-center justify-between">
        <div>
          <span
            class="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-yellow-600 bg-yellow-200"
            v-text="stateOfTask.state"
          />
        </div>
        <div class="text-right">
          <span class="text-xs font-semibold inline-block text-yellow-600">
            {{ stateOfTask.current }}/{{ stateOfTask.total }}
          </span>
        </div>
      </div>
      <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-yellow-200">
        <div
          :style="'width:' + progress + '%'"
          class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-yellow-500"
        ></div>
      </div>
    </div>
    <div v-else class="w-full grid grid-cols-3">
      <span class="col-span-3 font-bold">SwitchPortID</span>
      <span class=""> {{ stateOfTask.result.switchportid }}</span>
      <span>→</span>
      <span class="">{{ stateOfTask.result.switchportid_new }}</span>
      <span class="col-span-3 font-bold mt-0.5">UserPortID</span>
      <span class="">{{ stateOfTask.result.userportid }}</span>
      <span>→</span>
      <span class="">{{ stateOfTask.result.userportid_new }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, computed } from "vue";
import { useIntervalFn } from "@vueuse/core";
import { getStateOfTask, StateOfTask } from "../api";

export default defineComponent({
  name: "VTaskState",
  props: {
    taskID: {
      type: String,
      required: true,
    },
    apName: {
      type: String,
      required: true,
    },
  },
  setup(props: { taskID: string; apName: string }) {
    const { taskID, apName } = toRefs(props);

    const stateOfTask = reactive<StateOfTask>({
      state: "",
      current: "",
      total: 0,
      status: "",
    });

    const { pause } = useIntervalFn(
      async () => {
        const s = await getStateOfTask(taskID.value);
        Object.assign(stateOfTask, s);
        if (s.result !== undefined) pause();
      },
      300,
      true
    );

    const progress = computed(
      () => (Number.parseInt(stateOfTask.current) / stateOfTask.total) * 100
    );

    return { stateOfTask, apName, progress };
  },
});
</script>

<style scoped></style>
