<template>
  <CloudIcon v-if="syncing == 'synced'" class="w-5 h-5" />
  <CloudArrowUpIcon v-else-if="syncing == 'detectedChanges'" class="w-5 h-5 cursor-pointer" @click="syncAll" />
  <ArrowPathIcon v-else-if="syncing == 'syncing'" class="w-5 h-5 animate-spin" />
  <ExclamationTriangleIcon v-else class="w-5 h-5 animate-[ping_1s_ease-in-out_3] text-red-500" />
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapState, mapActions } from "pinia";
import { useProtocolStore } from "@/stores/admin/protocol";
import { ArrowPathIcon, CloudArrowUpIcon, CloudIcon, ExclamationTriangleIcon } from "@heroicons/vue/24/outline";
</script>

<script lang="ts">
export default defineComponent({
  props: ["executeSyncAll"],
  watch: {
    executeSyncAll() {
      this.syncAll();
    },
    syncing() {
      this.$emit("syncState", this.syncing);
    },
    detectedChangeProtocol() {
      clearTimeout(this.protocolTimer);
      if (this.detectedChangeProtocol == false) {
        return;
      }
      this.setProtocolSyncingState("detectedChanges");
      this.protocolTimer = setTimeout(() => {
        this.synchronizeActiveProtocol();
      }, 10000);
    },
  },
  emits: {
    syncState(state: "synced" | "syncing" | "detectedChanges" | "failed") {
      return typeof state == "string";
    },
  },
  data() {
    return {
      protocolTimer: undefined as undefined | any,
    };
  },
  mounted() {
    this.$emit("syncState", this.syncing);
  },
  beforeUnmount() {
    if (!this.protocolTimer) clearTimeout(this.protocolTimer);
  },
  computed: {
    ...mapState(useProtocolStore, ["activeProtocolObj", "syncingProtocol", "detectedChangeProtocol"]),

    syncing(): "synced" | "syncing" | "detectedChanges" | "failed" {
      let states = [this.syncingProtocol];

      if (states.includes("failed")) return "failed";
      else if (states.includes("syncing")) return "syncing";
      else if (states.includes("detectedChanges")) return "detectedChanges";
      else return "synced";
    },
  },
  methods: {
    ...mapActions(useProtocolStore, ["synchronizeActiveProtocol", "setProtocolSyncingState"]),
    syncAll() {
      if (!this.protocolTimer) clearTimeout(this.protocolTimer);
      this.synchronizeActiveProtocol();
    },
  },
});
</script>
