<template>
  <span class="second-timer">
    {{ duration }}
  </span>
</template>

<script>
export default {
  name: "SecondTimer",
  data() {
    return {
      duration: "00:00:00",
      recordSecondCount: 0,
      setT: null,
    };
  },
  methods: {
    start() {
      this.setT = setInterval(() => {
        this.recordSecondCount++;
        this.duration = this.timeToText(this.recordSecondCount);
      }, 1000);
    },
    end() {
      this.pause();
      this.duration = "00:00:00";
      this.recordSecondCount = 0;
    },
    pause() {
      clearTimeout(this.setT);
      this.$emit("on-duration", this.recordSecondCount, this.duration);
    },
    timeToText(timeNumber) {
      const HOUR_TIME = 60 * 60;
      const MINUTE_TIME = 60;
      let [hour, minute, second] = [0, 0, 0];
      let residueTime = timeNumber;

      if (residueTime >= HOUR_TIME) {
        hour = Math.floor(residueTime / HOUR_TIME);
        residueTime -= hour * HOUR_TIME;
      }
      if (residueTime >= MINUTE_TIME) {
        minute = Math.floor(residueTime / MINUTE_TIME);
        residueTime -= minute * MINUTE_TIME;
      }
      second = residueTime;

      return [hour, minute, second]
        .map((item) => ("00" + item).substr(("" + item).length))
        .join(":");
    },
  },
  beforeDestroy() {
    if (this.setT) clearInterval(this.setT);
  },
};
</script>
