<template>
  <div class="timer">
    <div class="end" v-on:click="resetTime()">X</div>
    <p v-if="warning == false" class="timeleft reverse">{{ countDown.toString() }}</p>
    <p v-if="(warning == true) || (typeof warning == 'undefined')" class="timeout reverse">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
    </p>
    <button v-on:click="restartTimer" class="timerBtn"><span class="timerBtn-inner"></span></button>
    <p v-if="warning == false" class="timeleft">{{ countDown.toString() }}</p>
    <p v-if="warning == true || (typeof warning == 'undefined')" class="timeout">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
      <img src="joker.png" alt="joker">
    </p>
  </div>
</template>

<script>
var Interval;
export default {
  name: "Timer",
  props: {
    time: Number,
    playsound: Boolean,
  },
  data: function() {
    return {
      countDown: -2,
      warning: true,
      wakeLock: null,
    }
  },
  methods: {
    resetTime: function() {
      this.$emit('set-time', 0);
    },
    timeleft: function(){
      this.countDown--;
      if(this.countDown == 0) {
        this.warning = true

        if(this.playsound) {
          var audio = new Audio('timeout.wav');
          audio.play();
        }
        clearInterval(Interval);
      }

    },
    restartTimer: function() {
      if(this.wakeLock == null && 'wakeLock' in navigator) {
        this.wakeLock = navigator.wakeLock.request('screen');
      }
      this.countDown = this.time;
      this.warning = false;
      clearInterval(Interval);
      Interval = setInterval(() => {
        this.timeleft()
      }, 1000);
    }
  },
}
</script>

<style lang="scss" scoped>

.timer {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;

  .timeleft {
    font-size: 60px;
    padding: 23px 20px 84px 20px;
    margin: 10px 0;
    color: $black;
    background-image: url("~@/img/tile-back.svg");
    background-size: cover;
    text-align: center;
    width: 80px;
    height: 60px;
  }

  .timeout {
    margin: 40px;

    img {
      height: 3rem;
    }
  }

  .timerBtn {
    appearance: none;
    border: 1px solid $white;
    border-radius: 3px;
    font-size: 3rem;
    background: none;
    padding: 2rem;

    .timerBtn-inner {
      display: inline-block;
      height: 2rem;
      width: 8rem;
      background-color: $white;
    }
  }

  .reverse {
    transform: scale(-1, -1);
  }

  .end {
    display: block;
    position: absolute;
    right: 1px;
    top: 1px;
    font-size: 32px;
  }
}

</style>