Vue.component('event-count-down', {
  props: { 
    sys_request_time: {
      type: String,
    },
    sys_expiry_time: {
      type: String,
    },
    countdown: {
      type: Number,
      default: 600,
    }
  },
  inject: ['_f','_get'],
  data: () => ({
    count: 0,        
    timer: null,
    stopped: false,
    user_expiry_time: null,
  }),
  computed: {
    printCountDown() {
      let min = parseInt(this.count / 60);
      let sec = this.count - min * 60;
      if (sec <= 0)
        sec = 0;
      return `${min < 10?"0"+min:min}:${sec < 10?"0":""}${sec}`

    },
  },
  mounted () {
    this.count = this.countdown;
    this.user_expiry_time = new Date(this.sys_expiry_time) * 1 + new Date() * 1 - new Date(this.sys_request_time) * 1;
    this.checkTime(this.$t('event.timeout'));
  },
  methods: {
    get_user_expiry_count() {
      return (new Date(this.user_expiry_time) * 1 - new Date() * 1)/1000;
    },
    checkTime (text) {
      let _this = this;
      if (!this.stopped) {
        this.count = Math.floor(Math.max(0, Math.min(--this.count, this.get_user_expiry_count() || this.count)));
        if (this.count > 0) {
          this.timer = setTimeout(()=>{
            this.checkTime(text);
          }, 1000);
        } else {
          this.count = 0;
          this.stopped = true;
          this.popupTimeout(text);
        }
      }
    },
    popupTimeout (text = false) {
      let timeout_message = (text || this.$t('event.timeout'));
      let _this = this;
      swal(timeout_message, '', 'warning').then(() => {
        _this.$emit('timesup');
      });
    }
  },
  template:
`<div>
<div class="mt-2 mb-3" v-html="$t('event.timeLimit', {time:printCountDown})" style='padding:12px 20px; background: #fdfacf; border: 2px solid gold; border-radius: 3px;'></div> 
</div>`
});