<!--
    Copyright © 2021 Adrien Agez <adrien.agez@pm.me>

    This file is part of Nexus Timers.

    Nexus Timers is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Nexus Timers is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Nexus Timers.  If not, see <https://www.gnu.org/licenses/>.
-->

<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>
