<template>
  <div class="timer">
    <span v-if="displayHours">{{ hours }}:</span><span v-if="displayMinutes">{{ minutes }}</span><span>:{{ seconds }}</span>
  </div>
</template>

<script>
  'use strict'
  export default {
    name: 'Timer',
    data () {
      return {
        currentTime: this.$attrs.initialTime,
        timerIntervalId: null
      }
    },
    methods: {
      startTimer: function () {
        this.stopTimer()
        this.timerIntervalId = setInterval(() => {
          if (this.currentTime === 0) {
            this.stopTimer()
          } else {
            this.currentTime--
          }
        }, 1000)
      },
      stopTimer: function () {
        clearInterval(this.timerIntervalId)
      },
      setTime: function (time) {
        this.currentTime = time
      }
    },
    computed: {
      seconds: function () {
        return (this.currentTime % 60).toLocaleString('en', {minimumIntegerDigits: 2})
      },
      minutes: function () {
        let minutes = Math.floor(this.currentTime / 60) % 60
        return this.displayHours > 0
          ? minutes.toLocaleString('en', {minimumIntegerDigits: 2})
          : minutes
      },
      hours: function () {
        return (Math.floor(this.currentTime / 3600) % 24)
      },
      displayMinutes: function () {
        return this.minutes > 0 || this.hours > 0
      },
      displayHours: function () {
        return this.hours > 0
      }
    },
    mounted () {
      this.startTimer()
    }
  }
</script>

<style scoped>

</style>
