<template>
  <span>{{ time }}</span>
</template>

<script>
export default {
  props: {
    value: {
      type: Object,
      default() {
        return {
          time: 60,
          start: true
        }
      }
    }
  },
  data() {
    return {
      interval: null,
      index: 0,
      time: 60,
      start: true
    }
  },
  watch: {
    'value.time'(val) {
      this.time = val
    },
    'value.start'(val) {
      this.start = val
    },
    time(val) {
      let options = {
        time: val,
        start: this.start
      }
      this.$emit('input', options)
    },
    start(newVal, oldVal) {
      if (newVal === true && oldVal === false && this.time > 0) {
        this.tick()
      }
      if (newVal === false && oldVal === true) {
        this.stop()
      }
      let options = {
        time: this.time,
        start: newVal
      }
      this.$emit('input', options)
    }
  },
  created() {
    this.time = this.value.time
    this.start = this.value.start
    if (this.start) {
      this.tick()
    }
  },
  methods: {
    tick() {
      this.interval = setInterval(() => {
        if (this.time > 0) {
          this.time--
        } else {
          this.stop()
          this.index++
          this.$emit('on-finish', this.index)
        }
      }, 1000)
    },
    stop() {
      clearInterval(this.interval)
    }
  }
}
</script>
