<template>
  <qf-button @click="onClick" ref="button" :disabled="isDisabled" v-bind="$props" :size="size">
    <span>{{display}}</span>
  </qf-button>
</template>

<script>
import QfButton from '../../button';
import StringUtil from '../../util/string';
import LocaleMixin from '../../locale/mixin';

export default {
  name: 'QfCountButton',
  mixins: [LocaleMixin],
  components: {
    QfButton
  },
  props: {
    countText: {
      type: String,
      default: ''
    },
    text: {
      type: String,
      default: ''
    },
    count: Number,
    size: String,
    disabled: Boolean,
    autoStart: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      initCount: 60,
      timer: null
    };
  },

  computed: {
    isDisabled() {
      return this.disabled || this.timer !== null;
    },
    display() {
      if (this.timer) {
        return StringUtil.format(this.countText || this.t('qf.countbutton.count'), this.initCount);
      } else {
        return this.text || this.t('qf.countbutton.sendText');
      }
    }
  },

  mounted() {
    if (this.count) {
      this.initCount = this.count;
    }
  },

  beforeDestroy() {
    if (this.timer) {
      window.clearInterval(this.timer);
      this.timer = null;
    }
  },

  methods: {
    start() {
      if (!this.timer) {
        this.timer = window.setInterval(() => {
          this.initCount -= 1;
          if (this.initCount === 0) {
            this.stop();
          }
        }, 1000);
      }
    },

    stop() {
      window.clearInterval(this.timer);
      this.initCount = this.count;
      this.timer = null;
    },

    onClick() {
      if (this.autoStart) {
        this.start();
      }
      this.$emit('click');
    }
  }
};
</script>
