<template>
  <div>
    <span @click="edit" v-if="!isEditMode">
      {{ newProgress }} pages | {{ progress }}%
    </span>
    <span v-show="isEditMode">
      <input type="number" @keydown.esc="cancelEdit" @keydown.enter="submit" ref="readPagesInput" min="0"
             :max="totalPages" v-model.number="newProgress"/>
    </span>
  </div>
</template>

<script>
import {mapActions, mapGetters} from "vuex";
import {TURN_ON_EDIT_MODE, TURN_OFF_EDIT_MODE} from '../store/mutation-types'

export default {
  name: 'Progresseditor',
  props: {
    totalPages: Number,
    readPages: Number,
    bookId: Number
  },
  data() {
    return {
      newProgress: this.readPages
    }
  },
  computed: {
    progress() {
      return Math.round(this.newProgress / this.totalPages * 100);
    },
    ...mapGetters('bookprogressmodule', ['isEditMode'])
  },
  created() {
    this.newProgress = this.readPages;
  },
  methods: {
    ...mapActions('bookprogressmodule', [
      'updateProgress'
    ]),
    edit: function () {
      this.$store.commit('bookprogressmodule/' + TURN_ON_EDIT_MODE);
      setTimeout(() => this.$refs.readPagesInput.focus(), 1)
    },
    cancelEdit: function () {
      this.$store.commit('bookprogressmodule/' + TURN_OFF_EDIT_MODE);
    },
    submit: function () {
      this.$store.commit('bookprogressmodule/' + TURN_OFF_EDIT_MODE);
      this.updateProgress({'bookId': this.bookId, 'progress': this.newProgress});
    }
  }
}
</script>