<template>
  <div id="countdown">
    <div
      ref="countdownNumber"
      style="display: inline-block; line-height: 40px"
    ></div>
    <svg>
      <circle
        r="18"
        cx="20"
        cy="20"
      ></circle>
    </svg>
  </div>
</template>
<script>
export default {
  props: ["duration"],
  data() {
    return {
      timer: undefined,
      countdown: this.duration || 10,
    };
  },
  mounted() {
    this.$refs.countdownNumber.textContent = this.countdown;
    this.timer = setInterval(() => this.startCount(), 1000);
  },
  unmounted() {
    clearInterval(this.timer);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    startCount() {
      this.countdown -= 1;
      this.$refs.countdownNumber.textContent = this.countdown;
      if (this.countdown === 0) {
        clearInterval(this.timer);
        this.$emit("close");
      }
    },
  },
};
</script>
<style scoped>
#countdown {
  position: relative;
  margin: auto;
  height: 40px;
  width: 40px;
  text-align: center;
}
svg {
  position: absolute;
  top: 0;
  right: 0;
  width: 40px;
  height: 40px;
  transform: rotateY(-180deg) rotateZ(-90deg);
}
svg circle {
  stroke-dasharray: 113px;
  stroke-dashoffset: 0px;
  stroke-linecap: round;
  stroke-width: 2px;
  stroke: var(--bulma-primary);
  fill: none;
  animation: countdown 10s linear infinite forwards;
}
@keyframes countdown {
  from {
    stroke-dashoffset: 0px;
  }
  to {
    stroke-dashoffset: 113px;
  }
}
</style>
