<template>
  <transition name="bounce">
    <div
      v-if="isActive"
      class="
        container
        d-flex
        flex-row flex-wrap
        rounded
        bg-warning bg-gradient
        shadow
        p-3
        mt-lg-5
      "
      id="apache-monitor"
    >
      <span class="fw-bold m-auto me-2 ms-1">Apache: </span>
      <span
        v-if="isApacheNeedRestart && !isApacheRestartPending"
        class="badge rounded-pill bg-danger m-auto"
        >Нужен перезапуск</span
      >
      <span
        v-if="isApacheRestartPending"
        class="badge rounded-pill bg-success m-auto"
        >Перезапуск</span
      >
      <span class="flex-fill"></span>
      <button
        v-if="isApacheRestartPending"
        type="button"
        class="btn btn-success btn-sm align-self-end shadow"
        @click.prevent="fetchApacheRestartFlag"
        title="Обновить статус"
        v-tooltip:top
      >
        Обновить
      </button>
      <button
        v-if="isApacheNeedRestart && !isApacheRestartPending"
        type="button"
        class="btn btn-danger btn-sm align-self-end shadow mt-1 mb-1"
        @click.prevent="updateApacheRestartFlag"
        title="Перезапустить Apache"
        v-tooltip:top
      >
        Перезапустить
      </button>
    </div>
  </transition>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  data: () => ({
    is_locked: false,
  }),
  computed: {
    ...mapGetters([
      "isApacheNeedRestart",
      "isApacheRestartPending",
      "isApacheRestartFlagSent",
    ]),
    isActive() {
      return this.isApacheNeedRestart || this.isApacheRestartPending;
    },
  },
  methods: {
    ...mapActions(["updateApacheRestartFlag", "fetchApacheRestartFlag"]),
    async monitor_status() {
      if (this.is_locked) return;
      this.is_locked = true;

      while (this.isActive) {
        await new Promise((resolve) => setTimeout(resolve, 2000));
        await this.fetchApacheRestartFlag();
      }

      this.is_locked = false;
    },
  },
  watch: {
    "$store.getters.isApacheNeedRestart": function () {
      this.monitor_status();
    },
    "$store.getters.isApacheRestartPending": function () {
      this.monitor_status();
    },
  },
  async mounted() {
    if (this.isActive) await this.monitor_status();
    else await this.fetchApacheRestartFlag();
  },
};
</script>

<style scoped>
#apache-monitor {
  min-width: 30%;
  max-width: 40%;
}

.bounce-enter-active {
  animation: bounce-in 0.7s ease-out both;
}

.bounce-leave-active {
  animation: bounce-in 0.7s reverse ease-in both;
}

@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.25);
  }
  100% {
    transform: scale(1);
  }
}
</style>
