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

<script>
import {EventBus} from "../event-bus";
import axios from "axios";

export default {
  name: 'Progresseditor',
  components: {
    EventBus
  },
  props: {
    totalPages: Number,
    readPages: Number,
    bookId: Number
  },
  data() {
    return {
      editmode: false,
      newProgress: this.readPages
    }
  },
  computed: {
    progress() {
      return Math.round(this.newProgress / this.totalPages * 100);
    }
  },
  mounted() {
  },
  created() {
    this.newProgress = this.readPages;
  },
  methods: {
    edit: function () {
      this.editmode = true;
      setTimeout(() => this.$refs.readPagesInput.focus(), 1)
    },
    cancelEdit: function () {
      this.editmode = false;
    },
    submit: function () {
      this.editmode = false;
      axios.post('/progress/update', {
        bookId: this.bookId,
        progress: this.newProgress
      }, {
        headers: {
          'content-type': 'text/json'
        }
      }).then(() => {
        window.EventBus.$emit('updateProgress', {readPages: this.newProgress});
      })
    }
  }
}
</script>